简体   繁体   English

React.js:为什么子组件更改父状态?

[英]React.js: Why child component change parent state?

Why in this example child component changing parent component state? 为什么在此示例中子组件更改了父组件状态? According to the Facebook(react.js) docs State is similar to props, but it is private and fully controlled by the component. 根据Facebook(react.js)的文档,状态类似于道具,但是它是私有的,并且完全由组件控制。

codepen example 代码笔示例

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {data: this.props.data};
  }

  handleChange(event) {
    let updatedData = Object.assign({}, this.state.data);
    updatedData[event.target.name][event.target.dataset.lang] = event.target.value;

    this.setState({
      data: updatedData
    });
  }

  render() {
    return (
      <form>
          {Object.keys(this.props.data.titles).map((l, index) => 
          <input type="text" name="titles" data-lang={l} value={this.state.data.titles[l]} onChange={this.handleChange.bind(this)} />
          )}
      </form>
    );
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      images: [{"titles": {"en": "deluxe1500x930.jpg"}
      }],
      count: 1
    };
  }

  render() {
    return (
        <div>
          {Object.keys(this.state.images).map((x,index) => 
            <div>
              {this.state.images[x].titles.en}
              <NameForm data={this.state.images[x]} />
              <button onClick={(() => {this.setState({ count: 2 })}).bind(this)}>test</button>
            </div>
          )}
        </div>
    )
  }
}

Because you set the state with this.props.data . 因为您使用this.props.data设置状态。 the this.props.data came from the parent, therefore when it's changing so the state changes as well. this.props.data来自父级,因此,当它更改时,状态也随之更改。

The solution is simple, just set the state with new value (copied from this.props.data ) by using the spread operator instead of using the same reference. 解决方案很简单,只需使用传播运算符(而不是使用相同的引用)将状态设置为新值(从this.props.data复制)即可。

this.state = {data: ...this.props.data};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM