React Meteor 如何在 withTracker 数据到达后执行一个函数?

React Meteor How to execute a function after withTracker data arrives?

我正在从服务器发布数据并使用 withTracker 捕获它。

    export default withTracker(() => {
     let towndatasub = Meteor.subscribe("userTownDataPublisher",Meteor.userId());
  let resourcedatasub = Meteor.subscribe("userResourcePublisher",Meteor.userId());

      return{
    townData : Towns.find({"ownerId":Meteor.userId()}).fetch(),
    resourceData : Resources.find({"ownerId":Meteor.userId()}).fetch()

      }

    })(TownPage);

问题是我想 运行 一个函数,当 townData 和 resourceData arrives.If 我在 componentDidMount 中调用 updateResources 我在 this.props.componentWillReceive 属性上未定义 called.townData 和this.props.resourceData

updateResources = () =>{



Meteor.call("updateUserResources",Meteor.userId(),(err,result)=>{
if(err){
  console.log(err)
}else{
  console.log("asdasd");

      //console.log(this.props.resourceData); undefined
      // here i will do something with this.props.resourceData

}

})
      }

那么我应该在哪里调用 updateResources 函数才不会得到 undefined 呢?

首先,componentDidMount 仅在加载页面时调用一次,紧接在对 render 的第一次调用完成之后。因此,您不应该在那里调用 updateResources,因为届时集合可能还没有完成从服务器的加载。我建议在 render 中调用它,因为 render 将在数据到达之前调用一次,并在数据到达之后调用一次。

其次,如果您想在数据到达时更加准确,您可以 return withTracker 中涉及 ready 函数的另外两个属性,

export default withTracker(() => {
    let towndatasub = Meteor.subscribe("userTownDataPublisher",Meteor.userId());
    let resourcedatasub = Meteor.subscribe("userResourcePublisher",Meteor.userId());

    return{
        townData : Towns.find({"ownerId":Meteor.userId()}).fetch(),
        resourceData : Resources.find({"ownerId":Meteor.userId()}).fetch(),
        townsReady : towndatasub.ready(),
        resourcesReady : resourcedatasub.ready()
    }

})(TownPage);

然后在render中,只有当数据到达时才可以调用updateResources

if(this.props.townsReady && this.props.resourcesReady) {
    this.updateResources();
}