2017-08-16 73 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} />; 
} 
相關問題