【问题标题】:ReactJS: What is the correct way to set a state value as array?ReactJS:将状态值设置为数组的正确方法是什么?
【发布时间】:2018-01-24 13:43:32
【问题描述】:

我有一个使用 fetch API 获取用户数据的对象数组。我试过构造函数,创建一个函数,绑定它。它没有用。我试过 ComponentDidMount 和 setState,它返回 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}
        />
       );
    }
}

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

【问题讨论】:

标签: javascript node.js reactjs fetch-api


【解决方案1】:

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

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

然后使用

代替 that.state = {users: json}; 设置您的状态
that.setState({ users: json });

【讨论】:

  • 我不认为你想要状态对象周围的括号。应该是this.state = {users: []}
  • 我在记录的时候得到了数据。
  • 这里是示例数据: [ { "name": "Cars45 Test", "email": "test@cars45.com", "role": "Super Admin", "date": " 2-7-2017" }, { "name": "Jane Doe", "email": "janedoe@test.com", "role": "Super Admin", "date": "2-7-2017" }
  • 谢谢阿卜杜勒。在构造函数中初始化状态。
【解决方案2】:

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

that.setState({ users: json });

【讨论】:

  • @Olalekan 和console.log(json) 在控制台中显示什么?
【解决方案3】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    • 2022-12-03
    • 2020-10-02
    • 2016-12-29
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多