请问下,为何不能setTracerouteMsgs(prev => {xxx}
这样设置状态呢?
const [tracerouteMsgs, setTracerouteMsgs] = useState<TraceRouteMsg[]>([])
useEffect(() => {
console.log('result: ', tracerouteMsgs) // 这里不打印
}, [tracerouteMsgs])
...
<div>
<Button onClick={() => {
const tmpTracerouteMsgs = tracerouteMsgs
tmpTracerouteMsgs.push({
key: tracerouteMsgs.length + 1,
msg: []
})
setTracerouteMsgs(tmpTracerouteMsgs)
const key = tracerouteMsgs.length
global.ipcRenderer.send('traceroute-from-render', '8.8.8.8', key)
global.ipcRenderer.on(`traceroute-from-main-${key}`, (_, data) => {
console.log('mmkk: ', key, data)
setTracerouteMsgs(prev => {
const tmpPrev = prev
tmpPrev[1].msg = tmpPrev[1].msg.concat(data)
console.log('tmpPrev2:', tmpPrev)
return tmpPrev
})
})
}}>traceroute2测试</Button>
<span>tracetoute2结果:</span>
{
tracerouteMsgs[1]?.msg.map((item, index) => (
<>
<span key={index}>{item}</span> <br/>
</>
))
}
</div>
主要是这段代码的setTracerouteMsgs
貌似不生效:
setTracerouteMsgs(prev => {
const tmpPrev = prev
tmpPrev[1].msg = tmpPrev[1].msg.concat(data)
console.log('tmpPrev2:', tmpPrev)
return tmpPrev
})
是否不应该 return tmpPrev 还是怎么的呢?
我测试了简单的数据结构设置如:
const [tracerouteMsgs, setTracerouteMsgs] = useState([])
...
setTracerouteMsgs(prev => prev.concat(3))
这样可以生效。
但是为何修改内部的内容再设置就不生效呢?