Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何仅在meteor订阅完成后在react组件构造函数中设置初始状态值_Reactjs_Meteor_Constructor_Meteor Tracker - Fatal编程技术网

Reactjs 如何仅在meteor订阅完成后在react组件构造函数中设置初始状态值

Reactjs 如何仅在meteor订阅完成后在react组件构造函数中设置初始状态值,reactjs,meteor,constructor,meteor-tracker,Reactjs,Meteor,Constructor,Meteor Tracker,我正在使用React和Meteor作为我的应用程序。我需要使用集合中的记录初始化状态值,但是meteor订阅需要时间才能返回集合记录。由于获取订阅记录的延迟,组件构造函数中的状态值正在加载未定义的值。如何仅在订阅就绪后调用reacts构造函数。注意:订阅准备好后,我不想在render方法中设置状态值,我想在构造函数本身中设置状态值,以便可以将原始状态值与集合中的后续更新进行比较 class DataTable extends Component { constructor(props) {

我正在使用React和Meteor作为我的应用程序。我需要使用集合中的记录初始化状态值,但是meteor订阅需要时间才能返回集合记录。由于获取订阅记录的延迟,组件构造函数中的状态值正在加载未定义的值。如何仅在订阅就绪后调用reacts构造函数。注意:订阅准备好后,我不想在render方法中设置状态值,我想在构造函数本身中设置状态值,以便可以将原始状态值与集合中的后续更新进行比较

class DataTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      records: this.props.records
    };
    //since initially records were empty state value is initialised as undefined
    console.log(this.state.records);
  }

  render() {
return something
}
}
export default withTracker(() => {
  //withTracker seems to be giving some issue when rendering the component for first time
  //and giving empty values 
  Meteor.subscribe("records");
  return {
    records: Records.find({}).fetch()
  };
})(DataTable);

您可以通过引入一个中间的
组件来实现这一点,该组件在数据未准备好时进行渲染。它仅在组件具有数据时渲染组件。代码如下所示:

const Loader = props => {
  if (props.loading) return <div>Loading...</div>
  // This only gets rendered when we have data
  return <DataTable {...props} />
}

export default withTracker(() => {
  //withTracker runs twice - that is normal
  const subsHandle = Meteor.subscribe("records");
  const loading = !subsHandle.ready()
  return {
    loading, 
    records: Records.find({}).fetch()
  };
})(Loader); // Render the Loader component
const Loader=props=>{
如果(道具加载)返回加载。。。
//只有当我们有数据的时候,才会呈现它
回来
}
使用跟踪器导出默认值(()=>{
//withTracker运行两次-这是正常的
const subsHandle=Meteor.subscribe(“记录”);
常量加载=!subHandle.ready()
返回{
加载,
记录:records.find({}).fetch()
};
})(加载器);//渲染加载程序组件
这也意味着您的DataTable组件可以具有所需的PropType,例如
props.records