[英]Bind state to conditional statement inside of map function in React
I have a list of posts where clicking one will toggle the post and show its comments. 我有一个帖子列表,单击该列表可以切换该帖子并显示其评论。 I want the comments to load and show up conditionally based on whether or not the post is toggled, but I can't access state in my method checking if the post is toggled or not. 我希望根据帖子是否被切换来加载评论并有条件地显示评论,但是我无法在检查帖子是否被切换的方法中访问状态。
Isn't the context supposed to be bound automatically with arrow functions? 是否应该使用箭头功能自动绑定上下文?
var PostList = React.createClass({
componentDidMount() {
this.state = {};
const posts = this.props.posts;
posts.forEach(function(post) {
this.state[post._id] = false;
});
},
isToggled(post) {
return this.state[post];
},
render: function() {
var postList = posts.map((post,index) => (
<div class=“post”>
{post.content}<br/>
{this.isToggled(post._id) ?
<Comments postId={post._id}/>
:''}
</div>
))
}
Result: 结果:
TypeError: Cannot read property 'idyadayada' of null
USe this.setState outside the forEach
getInitialState(){
return {
}
}
componentDidMount() {
this.state = {};
const posts = this.props.posts;
var newState = {} ;
posts.forEach(function(post) {
newState[post._id] = false;
});
this.setState({
state: newState
}
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.