You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中基于对象实现子组件状态共享及跨子组件更新问题排查

Fixing Child Component Sync Issues in React

Hey there! Let's work through why your child components aren't updating in sync—great job diving into React this early, by the way.

The Root of the Problem

Right now, each Child component is storing a copy of the parent's obj in its own local state (in the constructor). Here's the catch: React only runs a component's constructor once, when it first mounts. When the parent updates its state.fieldObj, the child gets new props—but its local state doesn't automatically update to match. That's why only the child you click updates, while others stay stuck on old values.

The Fix: Single Source of Truth

React works best when shared state lives in a common parent component, and child components use props directly (instead of duplicating state). Let's simplify your code to follow this pattern:

  1. Remove local state from the Child component—we'll use props directly for rendering.
  2. Update the Child's update method to only trigger the parent's state change, since the parent will handle propagating the new value to all children.

Modified Code

Here's the adjusted version that syncs all child components automatically:

import React from 'react';
import { render } from 'react-dom';

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      filedStr: 'some text',
      fieldObj: { field1: true, field2: true }
    }
  }

  updObj = (which, val) => {
    this.setState(prevState => ({
      fieldObj: {
        ...prevState.fieldObj,
        [which]: val,
      },
    }));
  };

  render() {
    return (
      <div>
        <h2>Parent</h2>
        Value in Parent Component State: {this.state.fieldObj.field1 ? 1 : 0} : {this.state.fieldObj.field2 ? 1 : 0}
        <br />
        <Child obj={this.state.fieldObj} onUpdate={this.updObj} />
        <br />
        <Child obj={this.state.fieldObj} onUpdate={this.updObj} />
        <br />
        <Child obj={this.state.fieldObj} onUpdate={this.updObj} />
      </div>
    )
  }
}

class Child extends React.Component {
  // No more constructor or local state!
  update = (which) => {
    // Use the latest value from props, then call the parent's update method
    this.props.onUpdate(which, !this.props.obj[which]);
  };

  render() {
    // Render directly from props instead of local state
    return (
      <div>
        <h4>Child</h4>
        Value in Child Props: {this.props.obj.field1 ? 1 : 0} : {this.props.obj.field2 ? 1 : 0}<br />
        <button type="button" onClick={() => this.update('field1')}>field1</button>
        <button type="button" onClick={() => this.update('field2')}>field2</button>
      </div>
    )
  }
}

render(<Parent />, document.getElementById('root'));

Why This Works

  • Single Source of Truth: All child components rely on the parent's state.fieldObj as the single source of data. When the parent updates this state, every child receives the new props and re-renders automatically.
  • Less Code, Fewer Bugs: By removing local state from children, we eliminate the risk of state duplication and out-of-sync values.

For future reference: If you ever need temporary state in a child (like a form input that hasn't been saved yet), local state is totally fine. But for state that needs to be shared across components, keep it in a common parent (or later, use tools like Context API or Redux as you scale).

内容的提问来源于stack exchange,提问作者Fco Javier Snchez-Ostiz Erviti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:45:41