Fetching data in react

只愿长相守 提交于 2020-01-15 09:39:13

问题


I am new to react, so I am not sure how to call it. As a result, I apologize if this question was asked before. What I probably want to do is maping data, but I am not sure how to do it.

componentDidMount() {
    fetch("https://reqres.in/api/users?page=3")
    .then(data => {return data.json()})
    .then(datum => this.setState({client:datum.data}));
}

Above is my fetch component. The data that is taken from the API include the id, lastname, firstname. However, I want to assign id as slug instead and then change firstname+lastname into name

So, instead of seeing this inside the client array,

id:7
first_name:"Michael"
last_name:"Lawson"

I want to see something like this:

slug:7
name:"Michael Lawson"

回答1:


This is actually a JavaScript question.

Assuming you're receiving something like this from your API call:

data = [
  { id: 7, first_name: 'Michael', last_name: 'Lawson' },
  { id: 8, first_name: 'Joshua', last_name: 'Milton' },
]

You can simply use Array.map() to create a new array like the following example:

componentDidMount() {
  fetch("https://reqres.in/api/users?page=3")
    .then(data => { return data.json() })
    .then(datum => {
      const results = datum.data.map(x => {
        return {
          slug: x.id,
          name: x.first_name + ' ' + x.last_name
        }
      })
      this.setState({ client: result });
    });
}

Hope this help!




回答2:


This can be useful for you:

const list = [
  {
    id: 7,
    first_name: 'Michael',
    last_name: 'Lawson',
  },
];

function dataToState(data) {
  return data.map(item => {
    const { id: slug, first_name, last_name } = item;
    return { slug, name: first_name + ' ' + last_name };
  });
}

console.log(dataToState(list));



回答3:


If API response is simple you can write your own function and map it there. But if there is lots of data and you have to do map almost every field you can use GRAPHQL. Best way to create service that will make API call and response will go to graphql(Where your schema is written) and it will return you mapped values.



来源:https://stackoverflow.com/questions/50980378/fetching-data-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!