React父组件修改状态后更新的props未传递到子组件且不重渲染怎么办
问题原因及解决方案
核心原因
- 子组件
constructor生命周期仅在首次挂载前执行1次:你在constructor中打印props.dataProps、将props赋值给本地变量/state的操作,只会使用首次传入的初始props。后续父组件state更新、传入的props发生变化时,constructor不会重新触发,因此你在这里只能拿到初始的initialData,这属于对类组件生命周期的常见误解,不存在props未传递的问题。 - 实际上父组件调用
setState更新data后,自身会触发重渲染,会将最新的newData作为dataProps传入子组件,普通Component类的子组件默认会触发重渲染,你只是没在正确的位置获取更新后的props。
验证方法
你可以在子组件的render方法或componentDidUpdate生命周期中打印props,即可看到更新后的值,示例代码如下:
class ChildComponent extends Component { constructor(props) { super(props); const getData = props.dataProps; // 仅首次挂载执行,只会打印initialData console.log("constructor 中的getData: ", getData) this.state = {} } // 监听props变化,props更新时自动触发 componentDidUpdate(prevProps) { if (prevProps.dataProps !== this.props.dataProps) { // 这里会打印更新后的newData console.log("更新后的props: ", this.props.dataProps) // 如果你需要将props同步到子组件自身state,可在此处调用setState } } render() { // 每次重渲染都会拿到最新props,第一次打印initialData,第二次打印newData console.log("render 中的dataProps: ", this.props.dataProps) return <div>{this.props.dataProps}</div> } }
额外注意
如果你的子组件继承自PureComponent,且传入的props是引用类型(对象、数组等),直接修改原引用的值不会触发子组件重渲染,需要返回全新的引用才能触发更新,当前场景传入的是字符串基本类型,不存在该问题。
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

