ReactJS:将状态值设置为数组的正确方法是什么? [英] ReactJS: What is the correct way to set a state value as array?
本文介绍了ReactJS:将状态值设置为数组的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个使用fetch API获取用户数据的对象数组。我试过构造函数,创建一个函数,绑定它。它没用。我尝试了ComponentDidMount和setState,它返回undefined。
I have an array of object that get users data using fetch API. I have tried constructor, create a function, bind it. It didn't work. I tried ComponentDidMount and setState, it returns undefined.
class Admin extends Component {
componentDidMount () {
var that = this;
fetch('http://localhost:4500/data/users', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}).then(function(response) {
return response.json();
}).then(function(json){
console.log(json);
that.state = {users: json};
});
}
render() {
return (
<SpicyDatatable
tableKey={key}
columns={columns}
rows={this.state.users}
config={customOptions}
/>
);
}
}
将状态值设置为的正确方法是什么数组并渲染它?谢谢
What is the correct way to set a state value as array and render it? Thanks
推荐答案
首先在你的构造函数中初始化你的状态
First initialize your state in your constructor like this
constructor(props) {
super(props);
this.state = {users : []} //initialize as array
}
然后代替 that.state = {users:json};
使用
that.setState({ users: json });
这篇关于ReactJS:将状态值设置为数组的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文