简体   繁体   English

React state 在使用 React useContext 挂钩进行调度调用后未更新

[英]React state is not updated after dispatch call using React useContext hook

Yow guys, React beginner here.各位,这里是 React 初学者。
So basically, I am trying to fetch the updated state using React useContext hook.所以基本上,我正在尝试使用 React useContext钩子获取更新的 state。

The state is set inside a function call where the dispatch is placed, and the function call is bind to the button onClick event. state设置在ZC1C1C425268E68E68385D1AB5074C174C174C174C174F14F调用中,放置了ZC1C1C1C1C425268EBY68E68E68EBY68EB5014C5174C5174C5174C174C174C174C174C174C174C174C174C174C174C174C174C174C1AB5174C1ABANCAB51AR。

The function where the dispatch is called:调用 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
  }

Reducer:减速器:

case "LOCATION_FETCHED": {
      return {
        ...state,
        location: payload,
      }
    }

The function call in the component:组件中的 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
      })
  }

Button onClick function bind:按钮 onClick function 绑定:

onClick={() => getLocation(143)}

I'm not sure what is happening, the first click will log nothing but on the second click, I got the updated location state.我不确定发生了什么,第一次单击不会记录任何内容,但在第二次单击时,我得到了更新的位置 state。

As the comments say, the dispatch works asynchronously.正如评论所说,调度是异步工作的。 So if you want to know the new value you should use the useEffect hook like this.所以如果你想知道新的值,你应该像这样使用 useEffect 钩子。

useEffect(() => {
  console.log(location)
}, [location])

You can read more about here: https://reactjs.org/docs/hooks-effect.html您可以在此处阅读更多信息: https://reactjs.org/docs/hooks-effect.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM