admin管理员组文章数量:1429693
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 {
ponentDidMount () {
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
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 {
ponentDidMount () {
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
Share Improve this question edited Aug 16, 2017 at 12:12 Paul Fitzgerald 12.1k4 gold badges45 silver badges57 bronze badges asked Aug 16, 2017 at 12:06 OlalekanOlalekan 4756 silver badges22 bronze badges 1- 3 Possible duplicate of reactjs how to update state – Mayank Shukla Commented Aug 16, 2017 at 12:09
3 Answers
Reset to default 4First initialize your state in your constructor like this
constructor(props) {
super(props);
this.state = {users : []} //initialize as array
}
Then instead of that.state = {users: json};
set your state using
that.setState({ users: json });
You should use the React setState()
method.
that.setState({ users: json });
You already got the answer to use setState({ users: json })
, which is right.
As an alternative to initializing the array value like abul said, you could also do a conditional render, depending on the ponent state. I.e you can render a different ponent if the users aren't loaded yet.
render() {
const users = this.state.users;
return !users ?
<p>Loading..</p> :
<YourComponent users={users} />;
}
本文标签: javascriptReactJS What is the correct way to set a state value as arrayStack Overflow
版权声明:本文标题:javascript - ReactJS: What is the correct way to set a state value as array? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745499214a2660951.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论