0

我在我的应用程序中使用 React 和 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);
4

1 回答 1

1

您可以通过引入一个中间<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 组件可以具有所需的 PropTypes,例如props.records

于 2019-09-30T10:18:02.467 回答