小编典典

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

reactjs

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

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

将状态值设置为数组并将其呈现的正确方法是什么?谢谢


阅读 331

收藏
2020-07-22

共1个答案

小编典典

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

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

然后,而不是that.state = {users: json};使用

that.setState({ users: json });
2020-07-22