ReactJS: What is the correct way to set a state value as array?

天涯浪子 提交于 2019-12-02 04:49:21

问题


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


回答1:


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



回答2:


You should use the React setState() method.

that.setState({ users: json });



回答3:


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 component state. I.e you can render a different component if the users aren't loaded yet.

render() {
   const users = this.state.users;
   return !users ?
      <p>Loading..</p> : 
      <YourComponent users={users} />;
}


来源:https://stackoverflow.com/questions/45713138/reactjs-what-is-the-correct-way-to-set-a-state-value-as-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!