【发布时间】:2019-04-11 05:47:21
【问题描述】:
我对 React 很陌生,我正在尝试通过构建一个简单的笔记应用程序来练习。据我所知,一切都很好,但是!我读到状态不应该手动更新,所以我正在复制我的状态数组并过滤掉删除操作的结果。
但它失败了!相反,如果我控制台日志,它会正确地从状态数组中删除要删除的元素,但是,当我在副本上调用 setState() 以更新我的视图时,列表是错误的!
由于某种原因,我的 React 列表总是在视觉上从页面中删除最后一个元素,然后出现与我的状态不同步。
应用程序本身是一个带有嵌套列表和列表项组件的表单容器,它们使用表单类中的道具进行管理。
我做错了什么?
表单类
class NotesForm extends Component {
constructor(props) {
super(props);
const list = [
{ text: "Build out UI" },
{ text: "Add new note" },
{ text: "delete notes" },
{ text: "edit notes" }
];
this.state = {
'notes': list
};
// this.notes = list;
this.handleSubmit = this.handleSubmit.bind(this);
this.deleteNote = this.deleteNote.bind(this);
}
handleSubmit(e) {
e.preventDefault();
if (this.input.value.length === 0) { return; }
this.state.notes.push({text: this.input.value});
this.setState({ notes: this.state.notes });
this.input.value = "";
}
// BUG - deletes WRONG note!!
deleteNote(note) {
console.log({'DELETE_NOTE': note.text})
// var list = _.clone(this.state.notes);
var list = [...this.state.notes];
var filteredNotes = _.filter(list, function(n) {
return (n.text !== note.text);
})
console.log({
'list': list,
'filteredNotes': filteredNotes
})
this.setState({ notes: filteredNotes });
}
render() {
return (
<div className="row notes-form">
<div className="col-xs-12">
<form onSubmit={this.handleSubmit}>
<input type="text" className="new-note-input" ref={(input) => this.input = input} />
<br />
<button className="add-btn btn btn-info btn-block" type="button" onClick={this.handleSubmit}>Add</button>
<br />
<NotesList notes={this.state.notes} deleteNote={this.deleteNote} />
</form>
</div>
</div>
);
}
}
列表类
class NotesList extends Component {
constructor(props) {
super(props);
}
render() {
return (
<ul className="notes-list">
{this.props.notes.map((n, index) => <NotesListItem key={index} note={n} deleteNote={this.props.deleteNote} />)}
</ul>
);
}
}
列表项类
class NotesListItem extends Component {
constructor(props) {
super(props);
this.state = {
'text': props.note.text
};
this.delete = this.delete.bind(this);
}
delete() {
this.props.deleteNote(this.props.note);
}
render() {
return (
<li className="notes-list-item">
<span className="item-text">{this.state.text}</span>
<div className="notes-btn-group btn-group" role="group">
<button className="delete-btn btn btn-danger" type="button" onClick={this.delete}>×</button>
</div>
</li>
);
}
}
【问题讨论】:
-
NotesForm 中未定义变量“list”,请将您的 App 组件添加到您的帖子中。或者更好:使用codesandbox.io 创建您的错误演示并分享链接。
-
糟糕!我已经编辑并添加了用于“列表”的常量。我也会看看在代码沙箱上设置这个,谢谢!
标签: javascript reactjs state render