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

标签 javascript mongodb reactjs meteor

这个让我难住了,我正在使用 Tracker.autorun 函数来监听我的 Mongo 订阅何时准备好查询(根据上一篇 Meteor subscribe callback 的建议)。这似乎工作正常,因为它会在几秒钟后触发,表明 meteor 订阅已准备就绪。但是,当我尝试检查 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
}

最佳答案

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

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

除此之外,我在构造函数中初始化状态,然后在 componentWillMount() 中使用 this.setState() 设置它们

关于javascript - 为什么我无法在 Tracker.Autorun 中访问 React 状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39870820/

相关文章:

javascript - 如何使用react-hook复制基于类的组件异步setState方法

javascript - 不想返回整个对象,如何过滤掉我不想要的东西?

javascript - Mongo 日期范围查询 (GMT)

mongodb - 为什么 MongoDB 中的事务必须使用副本集?

ruby-on-rails - docker-compose mongo rails 连接失败

reactjs - react Webpack。为什么从子组件调用函数时会出现错误?

node.js - 类型错误 : Cannot read property 'map' of undefined in reactjs

javascript - 使用三元运算符如何检查值来自哪个 $stateParams?

javascript - 测试调用返回 promise 的函数的函数

javascript - 在 sencha Touch 中将商店中的项目动态加载到选项卡面板