简体   繁体   English

当我在 state 中放入道具时,即使更新了道具,state 也不会更新

[英]When I put props in state, state is not updated even if props is updated

When a parent component passes a props named title to a child component and puts the props into the child component's state, when the parent component's title is moved to the child component instead, the props is updated, but the state is not updated and the past title is retained.当父组件将一个名为title的props传递给子组件,并将props放入子组件的state中,当父组件的title改为移动到子组件时,props会更新,但state并没有更新过去标题被保留。

Props are updated, but the State using Props is not updated.道具更新了,但是使用道具的State没有更新。

How do I update the state of a child component when the parent component is updated?更新父组件时,如何更新子组件的state?

constructor() {
        super();
        this.state = {
            title:''
        };
    }

<Child title={this.state.title}/>)}
constructor(props) {
        super(props)
        this.state = {
            title: props.title
        };
    }

Don't store the same state in multiple locations;不要在多个位置存储相同的 state; synchronizing them will be a pain.同步它们会很痛苦。 Instead, pass down the title and a state setter function to the child, eg:相反,将标题和 state 设置器 function 传递给孩子,例如:

<Child
  title={this.state.title}
  setTitle={title => { this.setState({ title }); }}
/>

And don't keep state in the child - only use the title prop.并且不要在孩子中保留 state - 仅使用title道具。 Call the setTitle prop when you need to update from the child.当您需要从孩子更新时调用setTitle道具。

Copying props to state seems redundant and anti-pattern, but if you need to do it (for reasons like editing details in a form), you can copy the props into state using constructor and update (conditionally) it when the props' value is changed using componentDidUpdate lifecycle method:将道具复制到 state 似乎是多余且反模式的,但是如果您需要这样做(出于在表单中编辑详细信息等原因),您可以使用constructor将道具复制到 state 并在道具的值为时(有条件地)更新它使用componentDidUpdate生命周期方法更改:

class Child extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: this.props.title // Copy
    };
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.props.title !== prevProps.title) {
      this.setState({
        title: this.props.title // Update conditionally when it is changed in props
      });
    }
  }

  render() {
    return <>{this.state.title}</>;
  }
}

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

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