我有待办事项列表,如果我单击“编辑”,它会渲染文本区域,然后单击“关闭”按钮,它会变回待办事项,但是,这里的错误是,如果我单击第一个待办事项的编辑按钮,然后当我单击第二个待办事项的编辑按钮,它将更改第一个待办事项的isEdit
状态值,从而重新呈现待办事项列表。我以为可能会在每次触发handleEditClick
函数时进行预检查,以确保ID是否已存在于关闭状态数组中。我以为也许我可以设置一个全局变量来检查函数是否被调用过一次,然后一旦将全局变量设置为true
,我就可以检查ID是否存在于关闭状态数组中,现在我有了在render方法中陷入状态状态,但我仍然无法弄清楚如何使这项工作有效。请提出建议,谢谢!。
这是我的代码:
let globalVar = false;
let closeObj = {id: '', isEdit: false};
class Form extends React.Component {
// ...
handleEditClick = (e, id, text) => {
globalVar = true;
let { val, close } = this.state;
val.push(id);
this.setState({ val });
closeObj.id = id;
closeObj.isEdit = !closeObj.isEdit;
close.push(closeObj);
if (globalVar && this.handleEditClick) {
close.findIndex(
x => (x.id === id ? alert("ID is present") : alert("ID is absent"))
);
}
this.setState({ close });
};
handleCloseClick = id => {
let { close } = this.state;
if (id == closeObj.id) {
closeObj.isEdit = !closeObj.isEdit;
}
this.setState({ close });
};
renderEdit(text, id) {
return (
<div>
<TextField
onChange={this.handleChange}
onKeyDown={this.handleKeyDown}
label=""
margin="normal"
value={text}
color="secondary"
/>
<IconButton>
<CloseIcon onClick={() => this.handleCloseClick(id)} />
</IconButton>
</div>
);
}
render() {
return (
<div>
{this.props.todos.map(todo => (
<div key={todo.id}>
{this.state.val.includes(todo.id) && this.state.close[0].isEdit ? (
this.renderEdit(todo.text, todo.id)
) : (
<EditButton
todo={todo}
val={val}
text={text}
close={this.state.close}
removeTodo={todo => this.removeTodo(todo)}
handleEditClick={(e, id, text) =>
this.handleEditClick(e, id, text)
}
updateTodo={todo => this.updateTodo(todo)}
/>
)}
</div>
))}
</div>
);
}
}