为什么我无法访问Tracker.Autorun中的React状态?

时间:2016-10-05 09:53:24

标签: javascript mongodb reactjs meteor

这个让我感到困惑,我使用Tracker.autorun函数来监听我的Mongo订阅何时可以查询(根据之前Meteor subscribe callback的建议)。这似乎工作正常,因为它会在几秒钟后触发,表明流星订阅准备就绪。但是当我尝试在Tracker.autorun函数中检查状态时,this.state是未定义的。我错过了一些明显的东西吗这有更好的模式吗?我已经遇到越来越多的这些问题,并开始考虑转向redux ...任何建议都非常感谢!!

export default class BulkMapWrapper extends TrackerReact(React.Component) {

constructor() {
super();
this.state = {
  }

}

componentDidMount(){
const subscription =  Meteor.subscribe("allAuthors",{sort: {_id:-1}})
this.state = {
ready: subscription.ready(),
authorData: subscription
}

Tracker.autorun(function(){
if (subscription.ready()) {
  console.log("the subscription is ready");
  console.log(this.state)  //this is undefined
}

1 个答案:

答案 0 :(得分:1)

我正在使用箭头功能访问Meteor Tracker中的状态:

Tracker.autorun(() => {
    if (subscription.ready()) {
        console.log("the subscription is ready");
        console.log(this.state)  //this is undefined
     }
 });

除此之外,我在构造函数中初始化我的状态,然后在componentWillMount()

中使用this.setState()设置它们