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

前端 未结 3 527
轻奢々
轻奢々 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条回答
  •  旧时难觅i
    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 });
    

提交回复
热议问题