当我将道具置于状态时,即使道具更新,状态也不会更新

时间:2021-03-31 13:51:26

标签: reactjs

当父组件将名为title的props传递给子组件并将props置于子组件的状态时,当父组件的title移动到子组件时,props会更新,但状态不会更新并保留过去的标题。

Props 更新了,但是使用 Props 的 State 没有更新。

父组件更新时如何更新子组件的状态?

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

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

2 个答案:

答案 0 :(得分:2)

不要在多个位置存储相同的状态;同步它们会很痛苦。相反,将标题和状态设置函数传递给孩子,例如:

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

并且不要在孩子中保留状态 - 仅使用 title 道具。当您需要从孩子更新时调用 setTitle 道具。

答案 1 :(得分:1)

将 props 复制到 state 似乎是多余的和反模式的,但如果您需要这样做(出于编辑表单中的细节等原因),您可以使用 {{1 }} 并在使用 constructor 生命周期方法更改 props 的值时更新(有条件地)它:

componentDidUpdate