在反应中获取数据 [英] Fetching data in react

查看:94
本文介绍了在反应中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的反应者,所以我不确定如何称呼它.因此,如果您之前曾提出这个问题,我深表歉意.我可能想做的是映射数据,但是我不确定该怎么做.

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

上面是我的提取组件.从API获取的数据包括id,lastname,firstname.但是,我想将id分配为slug,然后将firstname + lastname更改为name

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"

我想看到这样的东西:

slug:7
name:"Michael Lawson"

推荐答案

这实际上是一个JavaScript问题.

This is actually a JavaScript question.

假设您从API调用中收到了类似的信息:

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' },
]

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

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

希望获得帮助!

这篇关于在反应中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆