React父组件向子组件传JS对象后修改不同步及state为undefined问题
问题原因
你目前的代码存在3个核心错误,直接导致了状态异常:
- 父组件自定义了
constructor构造函数但未调用super(),违反ES6类继承规范,会导致父组件实例初始化失败,props传递链路异常,这是子组件拿到的props为undefined的核心原因。如果没有额外初始化逻辑,直接删除父组件的空constructor即可。 - 子组件构造函数调用
super()时未传入props参数,虽然你此处使用的是构造函数的形参props不受影响,但后续在子组件其他位置调用this.props都会拿到undefined,属于典型的基础语法错误。 - 你直接在
render()方法中对this.state直接赋值,违反React状态修改规则:所有状态修改必须通过this.setState()方法执行,直接修改state不会触发组件重渲染,还会导致渲染逻辑异常,同时render()阶段禁止修改状态,否则会触发无限重渲染问题。
修复后可正常运行的代码
// 父组件删除空constructor即可 class ParentComponent extends React.Component { render() { return <ChildComponent exampleObject={"Example"}> </ChildComponent> } } class ChildComponent extends React.Component { constructor (props) { // super必须传入props super(props); this.state = { myState: props.exampleObject } } render() { // 如要修改state请在生命周期/事件回调中通过this.setState执行,禁止在render内修改 console.log(this.state.myState); // 可正常输出Example return <div></div> } }
父子组件状态同步的正确实现
React遵循单向数据流规范,子组件不能直接修改父组件传入的props,要实现子组件修改同步到父组件,需按以下逻辑实现:
- 父组件将需要共享的对象存在自身的state中,同时编写修改该state的回调函数
- 父组件将共享state和修改回调一同通过props传递给子组件
- 子组件需要修改值时,调用父组件传入的回调函数,将新值回传给父组件
- 父组件触发自身state更新后,新的状态会自动同步到所有子组件
示例如下:
class ParentComponent extends React.Component { constructor(props) { super(props); // 父组件维护共享状态 this.state = { exampleObject: "Example" } // 绑定修改方法的this指向 this.updateExample = this.updateExample.bind(this); } updateExample(newVal) { this.setState({ exampleObject: newVal }) } render() { return <ChildComponent exampleObject={this.state.exampleObject} onUpdate={this.updateExample} > </ChildComponent> } } class ChildComponent extends React.Component { constructor (props) { super(props); } // 示例:点击按钮触发修改 handleClick() { // 调用父组件传入的回调通知父组件修改 this.props.onUpdate("Example 2"); } render() { console.log(this.props.exampleObject); return <button onClick={() => this.handleClick()}>修改值</button> } }
内容的提问来源于stack exchange,提问作者Ibrahim7
相关产品推荐
相关产品推荐

