我正在尝试在 React 中创建一个笔记应用程序。 当按下“添加注释”按钮并输入框中的值时,应用程序应添加新注释。
不幸的是,当我尝试将注释推送到列表并更新父状态时,更改不会反射(reflect)在屏幕或 react 调试器中。
将新注释推送到列表中可以在警报行中看到,但在其他任何地方都看不到。
这是包含原始笔记状态的父组件:
class NoteApplication extends React.Component {
constructor(props) {
super(props);
this.state = {
notes: Array(),
};
this.update = this.update.bind(this);
this.state.notes.push("Sample note");
}
update(notes) {
return () => {
this.setState({
notes: notes
});
}
}
render() {
return (
<div>
<h1>React Notes</h1>
<div class="InsertBarDiv">
<InsertBar
notes={this.state.notes}
update = {this.update}
/>
</div>
<div class="NotesDiv">
<Notes
notes={this.state.notes}
/>
</div>
</div>
)
}
}
这是子组件
class InsertBar extends React.Component {
constructor(props) {
super(props);
this.state = {value:''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
const notes = this.props.notes.slice();
notes.push(this.state.value);
this.props.update(notes);
alert(notes);
event.preventDefault();
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input class="noteInsertBar" type="text" name="" onChange={this.handleChange}/>
<input class="insertBut" type="submit" value="Add Note"/>
</form>
</div>
)
}
}
class Notes extends React.Component {
renderNote(i) {
return (
<div>
{this.props.notes}
</div>
)
}
render() {
return (
<div>
<h2>Notes:</h2>
<div class="FullNote">
{this.renderNote(1)}
</div>
</div>
)
}
}
我希望将注释推送到注释列表的副本,并将父状态设置为注释列表的新副本。
然后我希望这会显示在屏幕上。
最佳答案
这可能是由于您从 update
返回一个函数,因此您应该在调用 update
时调用 setState
:
update(notes) {
setState({ notes });
}
旁注:在 React 中处理数组时,应该避免使用 Array.push
。您这样做的方式很好,因为您在推送之前调用 slice
来复制数组,但如果您使用 concat
或展开运算符,您将不太可能无意中引入错误。
const notes = this.props.notes.concat(this.state.value);
或者:
const notes = [...this.props.notes, this.state.value];
关于javascript - 从子组件传递数据时父状态不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56918103/