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
1 个解决方案
#1
0
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
}
},
#1
0
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
}
},