[英]What's the best solution for re-rendering child components on props change in React?
I have a parent component that fetches data in componentDidMount() hook. 我有一个父组件,它在componentDidMount()挂钩中获取数据。 The state is setState() -d with this data.
该数据的状态为setState()- d。 Then I pass the data to the child components as props and set their state based on these props.
然后,我将数据作为道具传递给子组件,并根据这些道具设置它们的状态。 On the first render the props will be undefined because componentDidMount() hasn't executed yet.
在第一个渲染中,道具尚未定义,因为componentDidMount()尚未执行。 So, the child components get undefined props and the state is created with them.
因此,子组件获得未定义的道具,并使用它们创建状态。 When the data fetches in componentDidMount() new props are passed to the child components, but the state is already created with undefined props and nothing changes.
当在componentDidMount()中获取数据时,新的道具将传递到子组件,但是状态已经使用未定义的道具创建,并且没有任何变化。 So, I am aware of two solutions now:
因此,我现在知道两种解决方案:
Use componentWillRecieveProps() .
使用componentWillRecieveProps() 。 But this is now deprecated.
但是现在不建议这样做。
Use stateless child components.
使用无状态子组件。 Pass the data to them as props from the parent component and don't set a state(use the data from props), and when the parent does a setState() in componentDidMount() , this will cause a re-render to child components with new props and everything works.
将数据作为父级组件的道具传递给他们,并且不设置状态(使用道具中的数据),并且当父级在componentDidMount()中执行setState()时,这将导致子组件的重新渲染新的道具,一切正常。
Now, what if I want to have stateful child components? 现在,如果我想拥有有状态的子组件怎么办? I can't use the second method, and the first one is deprecated.
我不能使用第二种方法,而第一种方法已被弃用。 What is the best solution to accomplish this?
实现此目的的最佳解决方案是什么?
You can read this blog post . 您可以阅读此博客文章 。 In short a better approach would be to use fully uncontrolled component with key.
简而言之,更好的方法是使用完全不受控制的组件和密钥。
Here is a sandbox example 这是一个沙箱示例
static getDerivedStateFromProps(props, state)
is invoked right before calling the render method, both on the initial mount and on subsequent updates. 在初始安装和后续更新上都在调用render方法之前立即调用。 It should return an object to update the state, or null to update nothing.
它应该返回一个对象以更新状态,或者返回null则不更新任何内容。 This method exists for rare use cases where the state depends on changes in props over time.
此方法适用于状态依赖于道具随时间变化的罕见用例。
static getDerivedStateFromProps(nextProps, prevState){
if(nextProps.someValue!==prevState.someValue){
return { someState: nextProps.someValue};
}
else return null;
}
For more details enter link description here 有关更多详细信息,请在此处输入链接描述
Consider using the replacement for componentDidReceiveProps
, getDerivedStateFromProps
, if you have state within a component which is informed by the values of the props it receives. 如果组件中的状态由接收到的props的值告知,请考虑使用
componentDidReceiveProps
, getDerivedStateFromProps
的替换。
https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.