我是新来的反应,所以我不知道如何调用它。 其结果是,我很抱歉,如果这个问题被问过。 我可能想要做的就是马平的数据,但我不知道该怎么做。
componentDidMount() {
fetch("https://reqres.in/api/users?page=3")
.then(data => {return data.json()})
.then(datum => this.setState({client:datum.data}));
}
以上是我取的组成部分。 即从API取得的数据包括ID,姓氏,名字。 不过,我想给ID为塞代替,然后更改姓名+姓氏为名字
因此,而不是看到这个客户端阵列内,
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' },
]
你可以简单地使用数组。 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 });
});
}
希望这有助于!
这可能是对您有用:
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));
如果API的回应很简单,你可以编写自己的功能,有映射。 但是,如果有大量的数据,你需要做的地图几乎每一个领域,你可以使用GRAPHQL 。 创建服务,这将使API调用和响应将前往graphql(如果你的模式是写),它会回报你映射值的最佳方式。