【发布时间】: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() 而一次又一次地更新它?如果是这样,当传递给孩子的道具发生变化时,是否有任何生命周期方法执行?
提前致谢
【问题讨论】:
-
componentDidMount仅在组件第一次渲染时被调用。如果您需要对道具更改做出反应,请查看reactjs.org/docs/react-component.html#componentdidupdate -
请附上EditComponent和父组件的其余部分
标签: javascript reactjs