我是新来的反应者,所以我不确定如何称呼它。结果,我很抱歉以前是否提出过这个问题。我可能想做的是映射数据,但是我不确定该怎么做。

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


以上是我的提取组件。从API获取的数据包括ID,姓氏,名字。但是,我想将id分配为slug,然后将firstname + lastname更改为name

因此,与其在客户端数组中看到它,不如

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


我想看到这样的东西:

slug:7
name:"Michael Lawson"

最佳答案

这实际上是一个JavaScript问题。

假设您从API调用中收到了以下信息:

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


您可以简单地使用Array。map()创建一个新数组,如以下示例所示:

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 });
    });
}


希望有帮助!

关于javascript - 在 react 中获取数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50980378/

10-09 06:32
查看更多