当我点击触发subscribe()的按钮时,我试图将this.state.subscribe更改为相反的布尔值。我甚至没有管理更改this.state.subscribed的更改值,更少的单击按钮时呈现不同的文本。我尝试过replaceState并添加回调函数。不完全确定我应该在回调功能中加入什么,如果这就是我做错了。
SingleSubRedditList = React.createClass({
mixins: [ReactMeteorData],
getMeteorData: function(){
Meteor.subscribe('posts');
var handle = Meteor.subscribe('profiles');
return {
loading: !handle.ready(),
posts: Posts.find().fetch(),
profiles: Profiles.find({}).fetch()
};
},
getInitialState: function(){
var subscribed;
return {
subscribed: subscribed
};
},
populateButton: function(){
//fetch is cumbersome, later try and do this another way to make it faster
var profile = Profiles.find({_id: Meteor.userId()}).fetch();
if (profile.length > 0){
this.state.subscribed = profile[0].subreddits.includes(this.props.subreddit);
}
},
subscribe: function(){
this.setState({
subscribed: ! this.state.subscribed
}
);
},
renderData: function(){
return this.data.posts.map((post) => {
return <SinglePost title={post.title} content={post.content} key={post._id} id={post._id} />
});
},
render: function(){
this.populateButton()
return (
<div>
<button onClick={this.subscribe}>
<p>{this.state.subscribed ? 'Subscribed' : 'Click To Subscribe'}</p>
</button>
<p></p>
<ul>
{this.renderData()}
</ul>
</div>
);
} });
答案 0 :(得分:1)
您无法使用this.state.subscribed = ...
中的populateButton
来设置状态。试图直接改变状态会导致它表现得很奇怪。
您还使用未定义的变量初始化subscribed
。您应该将其初始状态设为true
或false
。