我有一个对象数组,可以使用 fetch API 获取用户数据。我尝试过构造函数,创建一个函数,然后绑定它。它不起作用。我尝试了 ComponentDidMount 和 setState,它返回未定义。
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}
/>
);
}
}
将状态值设置为数组并渲染它的正确方法是什么?谢谢
首先在构造函数中初始化你的状态,如下所示
constructor(props) {
super(props);
this.state = {users : []} //initialize as array
}
然后代替that.state = {users: json};
使用设置你的状态
that.setState({ users: json });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)