【问题标题】:React child component not re rendering when prop is changed [duplicate]更改道具时反应子组件不重新渲染[重复]
【发布时间】:2021-01-22 11:38:24
【问题描述】:

我正在做一个简单的待办事项应用程序,我尝试根据单击的注释的 id 呈现 EditComponent,以便我可以在编辑备注表格。 我将活动笔记 ID 存储在 父母的状态中。 EditComponent 第一次渲染时,它按预期工作。 但是,当我使用 setState 更改 id 时,现有的渲染不会使用新的注释详细信息进行更新。 这是在单击特定笔记的编辑按钮时执行的函数

  setEditState = id => {
    this.setState({id,isEdit:true})
  }

这是我的父渲染()

render() {
    let form;
    if(this.state.isEdit){
      form = <EditComponent id={this.state.id} />
    }
    else{
      form = <AddComponent />
    }
    return (
      <div className="App">
        <ViewComponent notes={this.state.notes} setEditState={this.setEditState} deleteNote={this.deleteNote} />
        {form}
      </div>
    );
  }

这里是我填充 EditComponent 状态的地方。

    async componentDidMount(){
        const note = await this.getNote(this.props.id)
        console.log(note.data.subject)
        this.setState({
            id:this.props.id,
            modifiedSubject: note.data.subject,
            modifiedNote: note.data.noteText
        })
    }

这是子渲染()中编辑表单中的输入之一

<input className="form-control" type="text" onChange={this.handleSubject} value={this.state.modifiedSubject} />

我的预感: 我是不是因为我使用了 componentDidMount() 而一次又一次地更新它?如果是这样,当传递给孩子的道具发生变化时,是否有任何生命周期方法执行?

提前致谢

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

你必须使用UNSAFE_componentWillReceiveProps() 。

Ref

【讨论】:

猜你喜欢
  • 2020-05-01
  • 2021-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 2021-07-13
相关资源
最近更新 更多