简体   繁体   English

上下文 state 不更新

[英]context state does not update

i am new to context api, I tried updating the context state by sending a dispatch to the reducer, but when i log the state, i get the default state. i am new to context api, I tried updating the context state by sending a dispatch to the reducer, but when i log the state, i get the default state. however when i inspected inside the react dev tools, i found the the state does have a changed state, but it's just not logging it out in the console, am i doing something wrong?但是,当我在 react 开发工具中进行检查时,我发现 state 确实有更改的 state,但它只是没有在控制台中将其注销,我做错了什么吗?

const State = ({ children }) => {
const initState = {
    trending: [],
    search: []
}
const [state, dispatch] = useReducer(Reducer, initState)

useEffect(() => {
    console.log(state.trending) //returns []
    dispatch({ type: 'LOAD_TRENDING', payload: ['some Data'] })
    console.log(state.trending); // returns [] instead of ['some Data']
    },
 [])}

React 开发者工具检查截图

You need to put state.trending in the dependency array in the useEffect.您需要将 state.trending 放入useEffect中的依赖数组中。 So your could would look like:所以你的可能看起来像:

    useEffect(() => {
        console.log(state.trending) //returns []
        console.log(state.trending); // returns [] instead of ['some Data']
      },
    [state.trending]) // this is new
    }

Also moving the dispatch to a seperate useEffect to avoid infinite rendering.还将调度移动到单独的 useEffect 以避免无限渲染。

useEffect(() => {
     dispatch({ type: 'LOAD_TRENDING', payload: ['some Data'] })
    },
 [])}

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

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