简体   繁体   中英

How to get data for a component

I have two pages (page1 and page2) with a SimpleTable component.

I have a page with a table for apples:

  render() {
    const props = this.props
    return (
      <Page {...props}>
        <SampleTable requestData={this.getApples} columns={[<columns for apples>]} />
      </Page>
    )
  }

And a page with a table for tomatoes:

  render() {
    const props = this.props
    return (
      <Page {...props}>
        <SampleTable requestData={this.getTomatoes} columns={[<columns for tomatoes>]} />
      </Page>
    )
  }

For reasons unknown to me, this particular child ( SampleTable ) is not being unmounted / mounted when I transition from page1 to page2 or vice-versa.

It is strange, since all the other children in all the other pages are being mounted / unmounted, even when I am using the same component for the children. So, clearly, I do not understand how / when does React decide to mount / unmount, or when does it decide to reuse a component. But I digress.

I will accept this fact: React will reuse children whenever it pleases.

My problem is that I am using Sampletable.componentDidMount to request data:

  componentDidMount() {
    console.log('SampleTable did mount. Requesting data ...')
    this.props.requestData(state.pageSize, state.page, state.sorted, state.filtered).then(res => {
      this.setState({
        data: res.rows,
        pages: res.pages,
        loading: false,
      })
    })
  }

But the function to request the data is provided by the parent, via props . I have the following problem:

  • on initial rendering, page1 provides a requestData=getApples via props to a SampleTable child.
  • SampleTable mounts and requests the data, using the getApples method provided by page1
  • I move to page2
  • page2 provides a different requestData=getTomatoes method to a SampleTable child
  • somehow Reacts decides that it can reuse the original component for this child and, since it is already mounted, componentDidMount is not called
  • and therefore, the new getTomatoes method is not called, and no data suitable for the tomatoes table is requested.

What am I doing wrong?

How can I ensure that the change in props is triggering a data reload?

You should try using a unique key attribute on your SampleData component while calling it, so that react knows it a different instance of your component and re-render it accordingly.

You can find more about keys here: https://reactjs.org/docs/lists-and-keys.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM