【发布时间】:2020-09-24 23:37:31
【问题描述】:
我有一个简单的 React Hooks 组件。当我尝试使用 setLightState 函数更新 lightState 时,它会为当前状态返回 undefined。访问返回体内的状态可以正常工作。
const MainControl = () => {
const [lightState, setLightState] = useState()
const [lightChan, setLightChan] = useState()
const updateLight = (newState) => {
setLightState({...lightState, ...newState})
}
useEffect(() => {
socket.connect()
let chan = socket.channel("lights:dioder")
chan.join().receive("ok", (response) => {
setLightState(response)
setLightChan(chan)
})
chan.on("light_colour", (resp) => {
updateLight(resp)
})
return () => {
chan.leave()
}
}, [])
if (!lightChan) return <h2>Loading...</h2>
return (
<h2>Lights are currently {lightState.on ? "on" : "off"}</h2>
)
}
updateLight 函数将lightState 读取为undefined,但返回主体不是?我认为这可能只在第一次渲染时才成立,但我不确定。
谢谢
【问题讨论】:
标签: javascript reactjs react-hooks