问题
When I am in a situation where I need pass a significant size of data to a child component, it seems the easiest way to do this is to store it in state and then pass it to children as props inside the render function. I am wondering if there is a less-intensive way to do this.
For instance, if I have a relationship like so:
<PhotosPage>
<PhotoFeed/>
</PhotosPage>
I know that I want to fetch the 'photo feed' data when the PhotosPage
mounts. Let's say I fetch this data in PhotoPage
's componentDidMount()
function. It seems so obvious to me that after the fetch request is completed to just set state, something like:
this.setState({feedData: response.data})
And then I can simply pass this.state.feedData
into the PhotoFeed
component as a prop
:
<PhotoFeed feedData={this.state.feedData} )}/>
This is a very basic example that does not include the rest of the complexity of the component. Is there a less state-intensive way to do this? I'm sure this is a very common container to view relationship and I want to know if there are any 'better' ways to do this without redux,etc. I just worry that I may be using state when I don't have to.
回答1:
This is generally an accepted method, the technique is called container components. Here is a good write-up about these.
Here is another discussing some different options.
来源:https://stackoverflow.com/questions/47185881/reactjs-should-a-parent-components-fetched-data-be-stored-in-state-to-pass-to