React Hooks如何更新嵌套状态数组并返回完整的原数组结构
问题原因
你之前的写法直接将目标会话的messages数组展开作为新的chats数组值,直接覆盖了整个chats的原始结构,丢失了其他会话数据和当前会话的非messages字段。
正确实现
推荐使用状态的函数式更新写法,规避状态stale问题,同时严格遵循React状态不可变的更新原则:
分步写法(可读性更高)
setChats(prevChats => { // 拷贝完整的原chats数组 const updatedChats = [...prevChats] // 拷贝需要修改的目标会话对象,保留其他字段 const targetChat = {...updatedChats[currentlyChatIndex]} // 追加新消息到messages数组 targetChat.messages = [...targetChat.messages, newMessage] // 替换回数组对应位置 updatedChats[currentlyChatIndex] = targetChat return updatedChats })
简写写法(基于数组map,更简洁)
setChats(prevChats => prevChats.map((chat, index) => index === currentlyChatIndex // 匹配下标时,返回新的会话对象,仅更新messages字段 ? {...chat, messages: [...chat.messages, newMessage]} // 不匹配下标时直接返回原对象,无修改 : chat ))
注意事项
建议给useState添加空数组初始值,避免初始状态为undefined时访问数组下标报错:
const [ chats, setChats ] = useState([])
内容的提问来源于stack exchange,提问作者Gabriel Caramés
相关产品推荐
相关产品推荐

