使用React useState时如何避免副作用



我的应用程序行为怪异,当我删除其中一个函数中的useState时,我发现它消失了。但是,我需要使用useState函数。

所以我正在创建一个ToDo应用程序,可以在其中添加、编辑和删除ToDo任务。除了当我想编辑一个现有的待办事项时,一切都很好。当我单击编辑按钮时,第一次不会发生任何事情。只有在第二次单击时,任务才会更改为编辑模式!

const [editme, setEditme] = useState(false)

function edit(e){
const editingItem = list.filter(obj => obj.id == e);
const el = document.getElementById('myInput')
el.value = editingItem[0].item
// --- this gets me in TROUBLE --- //
setEditme(true)
// ------------------------------- //
}
<ul>
{list.map((item)=>{
return(
<div className="li-all">
<li key={item.id}>{item.item}</li><div className="li-right"><FaPen onClick={()=>edit(item.id)}/><FaTrash onClick={()=>del(item.id)}/></div>
</div>
)
})}
</ul>
因此CertainPerformance和AWolf都是正确的。您永远不应该在React中直接操作DOM。使用useState,让React弄清楚它想要如何呈现它。

在我的案例中,我试图将待办事项(List Item <li>)直接复制到输入表单中,以允许用户编辑该项目。

错误( <li> -> <input>)

function edit(e){
const editingItem = list.filter(obj => obj.id == e);
const el = document.getElementById('myInput')
// WRONG //
el.value = editingItem[0].item
// ---- //
setEditme(true)
}

正确的方法是将其设置为状态,并使用状态将其传递到需要的位置。这看起来有违直觉,但本质上你是在让React找出如何最好地渲染前端。

校正( <li> -> getState/useState -> <input>)

function edit(e){
const [value, setValue] = useState('')
const editingItem = list.filter(obj => obj.id == e);
const el = document.getElementById('myInput')
// CORRECT //
setValue(editingItem[0].item)
el.value = value
// ---- //
setEditme(true)
} 

最新更新