2017-06-22 88 views
2

如何使用我的JSON數據更新狀態,然後將其輸出爲列表項?反應導入JSON文件,將內容存儲在狀態並呈現出來

我想使用componentDidMount()中的setState功能,以便在頁面加載時它存儲在狀態數據馬上和輸出在頁面上

import React from 'react'; 
import peopleData from '../persons.json'; 

class App extends React.Component { 
    constructor(){ 
    super(); 
    this.state = { 
     people: [] 
    } 
    } 

    componentDidMount(){ 
    console.log(peopleData); 
    } 

    render() { 
    return (
     <div> 
     <ul> 
      //Loop out this.state.people.names here as List Items 
     </ul> 
     </div> 
    ) 
    } 
} 

export default App; 

這裏是我的JSON數據即時導入到以上。

[ 
{ 
    "Name": "Lisa", 
    "Age": 100 
}, 

{ 
    "Name": "Bob", 
    "Age": 44 
}, 

{ 
    "Name": "Joe", 
    "Age": 17 
}, 

{ 
    "Name": "Jesper", 
    "Age": 6 
} 
] 

回答

3

難道你不能只將peopleData指定爲人物屬性的默認狀態嗎?它以同樣的方式工作,它更簡潔。

class App extends React.Component { 
    constructor(){ 
    super(); 
    this.state = { 
     people: peopleData, 
    } 
    } 

    render() { 
    const list = this.state.people.map(d => <li>{p.Name} - {p.Age}</li>); 
    return (
     <div> 
     <ul> 
      {list} 
     </ul> 
     </div> 
    ) 
    } 
} 
+1

哈哈非常感謝!我無法相信我沒有想到, –

+0

不客氣。請隨時接受這個答案 –