仅在流星订阅完成后如何在反应组件构造函数中设置初始状态值

how to set initial state values in react component constructor only after meteor subscription is complete

我正在为我的应用程序使用 React 和 Meteor。我需要使用集合中的记录来初始化状态值,但是流星订阅需要时间 return 集合记录。由于获取订阅记录的延迟,我在组件构造函数中的状态值正在加载未定义的值。我如何才能在订阅准备好后才调用反应构造函数。注意:我不想在订阅准备好后在 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);

您可以通过引入中间 <Loader> 组件来实现,该组件在数据未准备好时呈现。它只在有数据时渲染你的组件。代码将如下所示:

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

这也意味着您的 DataTable 组件可以具有所需的 PropType,例如 props.records