Fetching data in react

2019-08-09 03:16发布

问题:

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.