更新React中对象数组类型的state有没有更简洁的实现方式?
解决方案
完全可以,以下两种写法都可以省去额外变量声明,同时还能修正你原有写法中直接修改原状态对象的不规范问题(直接修改原状态对象可能会导致后续依赖状态比较的优化逻辑失效):
写法1:直接构造新对象
<textarea rows="2" value={questionList[number].question} onChange={(e) => { setQuestionList([ ...questionList.slice(0, number), // 直接基于原对象扩展生成新对象,覆盖question属性 { ...questionList[number], question: e.target.value }, ...questionList.slice(number + 1), ]); }} ></textarea>
写法2:函数式更新(更推荐)
如果存在闭包捕获旧questionList状态的风险(比如组件更新频繁、更新逻辑被延迟调用),更推荐用函数式更新的写法:
<textarea rows="2" value={questionList[number].question} onChange={(e) => { // 先存下输入值,避免合成事件复用导致异步访问取不到值 const inputValue = e.target.value; setQuestionList((prevList) => [ ...prevList.slice(0, number), { ...prevList[number], question: inputValue }, ...prevList.slice(number + 1), ]); }} ></textarea>
内容的提问来源于stack exchange,提问作者Nguyễn Tuấn Kiệt
相关产品推荐
相关产品推荐

