ReactJS:将状态值设置为数组的正确方法是什么?

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

我有一个对象数组,可以使用 fetch API 获取用户数据。我试过构造函数,创建一个函数,绑定它。它没有用。我尝试了 ComponentDidMount 和 setState,它 returns 未定义。

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

将状态值设置为数组并渲染它的正确方法是什么?谢谢

你应该使用 React setState() 方法。

that.setState({ users: json });

首先像这样在构造函数中初始化状态

constructor(props) {
        super(props);
        this.state = {users : []} //initialize as array
    }

然后使用

而不是 that.state = {users: json}; 设置您的状态
that.setState({ users: json });

您已经得到了使用setState({ users: json })的答案,这是正确的。

作为 abul 所说的初始化数组值的替代方法,您还可以根据组件状态进行条件渲染。也就是说,如果用户尚未加载,您可以呈现不同的组件。

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