2016-03-08 172 views
0

当我点击触发subscribe()的按钮时,我试图将this.state.subscribe改为与它相反的布尔值。我甚至没有管理改变this.state.subscribe的值,点击按钮时显示的文字更少。我试过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> 
); 

} });

回答

1

您不能使用this.state.subscribed = ...设置状态,您目前在populateButton中正在执行此操作。试图直接改变这种状态会导致它的行为异常。

您还在使用未定义的变量初始化subscribed。您应该给它初始状态truefalse

+0

我认为使用'='设置状态是做什么的。谢啦。只是最后一个问题。我试图根据Profile集合中的内容填充按钮HTML。但是我不能在getInitialState中做到这一点,因为数据还没有可用,所以我做了一个函数,我在填充按钮HTML并且它一直在工作的render方法中调用。自从取出'='它告诉我在现有状态转换期间无法更新(例如'render'内)。如何在getInitialState或其他位置填充按钮HTML? – ChrisWilson

+0

我对Meteor并不是很熟悉,但作为一个普通的React设计模式,您应该将外部资源作为Props传递给您的组件,而不是直接访问它们。由于无论何时将新的道具传递给组件,react都会重新呈现,因此可以确保在数据可用时正确初始化状态。 – gravityplanx