2017-08-16 63 views
2

我有一个使用抓取API获取用户数据的对象数组。我尝试过构造函数,创建一个函数,将其绑定。它没有工作。我试过ComponentDidMount和setState,它返回undefined。ReactJS:将状态值设置为数组的正确方法是什么?

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

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

+3

[reactjs如何更新状态]可能的复制(https://stackoverflow.com/questions/36527426/reactjs-how-to-update-state) –

回答

2

首先初始化状态在你的构造类似这样的

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

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

that.setState({ users: json }); 
+1

我不认为你想围绕状态对象的括号。它应该是'this.state = {users:[]}' –

+1

没错,更新了答案。谢谢 – abdul

+0

我在登录时获取数据。 – Olalekan

1

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

that.setState({ users: json }); 
+0

谢谢,刚才试了一下。它返回null。 – Olalekan

+0

@Olalekan和'console.log(json)'在控制台中显示的是什么? –

0

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

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

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