useContext不更新回调中的值

时间:2019-10-20 19:27:40

标签: javascript reactjs closures react-hooks

在附加到inner recursive function事件的回调中,

useConext的值未更新。我尝试进行控制台,但仍在打印静态值。但是在回调之外,它正在打印更新的值

wheel

2 个答案:

答案 0 :(得分:0)

安装时,侦听器使用函数变量初始化,该函数变量将appStore的第一个值包含在其词法范围内。

请参阅Closures

要对其进行修复,请将其移至useEffect范围内。

const Home = () => {
  const [appState, dispatch] = useContext(CTX);

  useEffect(() => {
    const fn = debounce(e => {
      dispatch({ type: 'INCREMENT_COMPONENT_COUNTER' });

      console.log(appState);
    }, 500);

    window.addEventListener('wheel', fn);
    return () => {
      window.removeEventListener('wheel', fn);
    };
  }, [appState]);
};

友善建议:

答案 1 :(得分:0)

您的debance函数在每个渲染器中都在变化,而useEffect仅捕获第一个渲染器,您可以使用useCallback修复此问题:

const Home = () => {
  // accessing my context
  const [appState, dispatch] = useContext(CTX)
  // printing updated value here (working perfect here)
  console.log(appState)

  // my callback on wheel event (also using debouce to queue burst of events)
  const fn = useCallback(
    () =>
      debounce(e => {
        // incrementing value ++1
        dispatch({ type: 'INCREMENT_COMPONENT_COUNTER' })
        // printing static value here (problem here)
        console.log(appState)
      }, 500),
    [appState, dispatch],
  )

  // setting and removing listener on component mount and unmount
  useEffect(() => {
    window.addEventListener('wheel', fn)
    return () => {
      window.removeEventListener('wheel', fn)
    }
  }, [fn])
}