第一次使用 ReactJS,在循环通过 AJAX 检索到的数据进行填充时遇到问题。我收到许多错误,包括 Uncaught TypeError: Cannot read property 'map' of undefined
。我应该设置 Prop 还是状态?
var Posts = React.createClass({
getInitialState: function() {
return ({
posts: []
})
},
loadPosts: function(){
var posts = null;
axios.get('/getposts')
.then(function (result) {
posts = result.data;
})
.catch(function (error) {
console.log(error);
});
},
postReadMode: function() {
return (
<div>
</div>
)
},
render: function() {
return (
<div>
Hello, {this.props.posts.map(function(item, i){
return item.title;
})}
</div>
)
}
})
返回的数据有点像多维对象/数组:
Obj:
0:
title: 'Title 1',
date: '12-2-2015',
content: 'asdf'
1:
title: 'Title 2',
date: '1-25-2016',
content: 'asdfasdf'
最佳答案
有两点我们需要澄清:
使用
{this.props.posts.map(..)
是不正确的。posts
(在本例中)是state
因为它的值已更改(在 AJAX 请求后从[]
更改为AJAX response
)。您必须使用{this.state.posts.map(...)
在render
方法。您应该在 componentDidMount 内实现 AJAX 调用方法:
If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
componentDidMount: function() {
var self = this;
axios.get('/getposts')
.then(function (result) {
self.setState({
posts: result.data
});
})
.catch(function (error) {
console.log(error);
});
}
设置setState
方法将更改 posts
状态值,因此 render
方法将再次运行以显示新的 UI。
如果您想要更好的方法来处理异步网络内容,请尝试 Redux AsyncActions .
关于javascript - ReactJS - 使用 map 循环遍历数据数组 Prop 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42149663/