使用fetch本地JSON档案,并且把它存在元件的state里面
在console.log的时候确实能看到JSON资料,不过却无法正确使用map渲染出来
JSON资料:
{
"items": [{ "id": "1", "name": "Tom" }, { "id": "2", "name": "Mary" }]
}
元件:
class Home extends React.Component {
state = {
data: []
};
componentWillMount = () => {
fetch("./data/one.json")
.then(res => res.json())
.then(result =>
this.setState({
data: result
})
);
};
render() {
const list = this.state.data.items;
return (
<div>
<h1>HOMEPAGE</h1>
{list.map((data, i) => (
<div key={i}>{data.name}</div>
))}
</div>
);
}
}
export default Home;