[英]How to use the updated state after setState call with react-hook
[英]React state is not updated after dispatch call using React useContext hook
各位,这里是 React 初学者。
所以基本上,我正在尝试使用 React useContext
钩子获取更新的 state。
state
设置在ZC1C1C425268E68E68385D1AB5074C174C174C174C174F14F调用中,放置了ZC1C1C1C1C425268EBY68E68E68EBY68EB5014C5174C5174C5174C174C174C174C174C174C174C174C174C174C174C174C174C174C1AB5174C1ABANCAB51AR。
调用 dispatch 的 function:
const fetchLocation = async (id: number) => {
const [, result] = await getLatestLocation()
dispatch({
type: "LOCATION_FETCHED",
payload: result
})
console.log(result) //this prints the latest/updated location even on button first click
}
减速器:
case "LOCATION_FETCHED": {
return {
...state,
location: payload,
}
}
组件中的 function 调用:
const {
fetchLocation,
location
} = React.useContext(locationContext)
const [fetchingLocation, setFetchingLocation] = useState(false)
const getLocation = (id: number) => {
fetchLocation(id)
.then(() => {
setFetchingLocation(true)
})
.finally(() => {
setFetchingLocation(false)
console.log(location) //this prints nothing or empty on the first button click
})
}
按钮 onClick function 绑定:
onClick={() => getLocation(143)}
我不确定发生了什么,第一次单击不会记录任何内容,但在第二次单击时,我得到了更新的位置 state。
正如评论所说,调度是异步工作的。 所以如果你想知道新的值,你应该像这样使用 useEffect 钩子。
useEffect(() => {
console.log(location)
}, [location])
您可以在此处阅读更多信息: https://reactjs.org/docs/hooks-effect.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.