道具更新时,使getDerivedStateFromProps的行为类似于componentDidMount

时间:2019-01-02 11:39:58

标签: javascript reactjs ecmascript-6 react-props react-component

我有React的父子组件,它们通过props进行通信,并且子组件通过Submit函数进行更新。

父类:

   handleSubmit = () => {
    this.setState({
      items: Items // imported from dummy data
    })
  }

  // truncated (inside render function, state destructuring, etc)

    <Form submit={this.handleSubmit} />
      <Table 
      data={items}
      currentCards={currentCards}
      currentPage={currentPage}
      totalPages={totalPages}
      />

儿童班:

// truncated (class Table, props constructor, set state from props)

   static getDerivedStateFromProps(props, state) {
    if (props.data !== state.data) {
      return {
        data: props.data
        };
      }
      return null;
    }

// truncated (inside render function, state destructuring, etc)

    <Pagination
      totalRecords={totalCards}
      pageLimit={10}
      pageNeighbours={1}
      onPageChanged={onPageChanged}
    />

      <tbody>
        {currentCards.map((item, key) => (
          <tr key={key || "0"}>
// truncated

分页的onPageChanged在第一次加载时启动,items仍然为空,但不是在按下handleSubmit时触发的(触发getDerivedStateFromProps处理项目/数据以填充{ {1}}。

我确认分页的currentCards不会在onPageChanged上启动,因为我在getDerivedStateFromProps内设置了一个断点,而孩子的Pagination内的data在提交时已经更新(但不需要render,因为它需要先启动currentCards

啊,我的onPageChanged代码也是基于this

简而言之,当使用Pagination检索数据时,如何重新计算分页?

更新

这里是CodeSandbox of what I'm trying to do,如果您单击提交,handleSubmit不会重新挂载

0 个答案:

没有答案