如何使用我的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
}
]
答案 0 :(得分:4)
你不能只将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>
)
}
}