ReactJS: Should a parent component's fetched data be stored in state to pass to children?

你说的曾经没有我的故事 提交于 2021-01-28 09:12:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!