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

前端 未结 3 512
轻奢々
轻奢々 2021-01-22 22:01

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

相关标签:
3条回答
  • 2021-01-22 22:17

    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 });
    
    0 讨论(0)
  • 2021-01-22 22:26

    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} />;
    }
    
    0 讨论(0)
  • 2021-01-22 22:36

    You should use the React setState() method.

    that.setState({ users: json });
    
    0 讨论(0)
提交回复
热议问题