useEffect 不会在路由更改时更新状态

新手上路,请多包涵

我正在寻找一种解决方案来注册路由更改并应用新的 state 使用 setStateuseEffect 。当路由更改时,下面的当前代码不会更新 setState 的功能。

For example, I register the pathname of / with location.pathname === '/' within createContext , if the pathname is / the setState of isHome is registered true , however if pathname is /page-1 setState 已注册 false

在浏览器重新加载时, onMount state 已正确设置,但是在使用 Link 进行路由更改时却没有。另外,请注意我正在使用 Gatsby 并在这样做时导入 { Link } from 'gatsby'

CreateContext.js

 export const GlobalProvider = ({ children, location }) => {

const prevScrollY = useRef(0);
  const [state, setState] = useState({
    isHome: location.pathname === '/',
    // other states
  });

  const detectHome = () => {
    const homePath = location.pathname === '/';
    if (!homePath) {
      setState(prevState => ({
        ...prevState,
        isHome: false
      }));
    }
    if (homePath) {
      setState(prevState => ({
        ...prevState,
        isHome: true
      }));
    }
  };

  useEffect(() => {
    detectHome();
    return () => {
      detectHome();
    };
  }, [state.isHome]);

  return (
    <GlobalConsumer.Provider
      value={{
        dataContext: state,
      }}
    >
      {children}
    </GlobalConsumer.Provider>
  );
};

If I console.log(state.isHome) on pathname / I get true , any other pathnames I get false , however, if我更改路线,当前 isHome 状态保持以前,直到我滚动并且 useEffect 应用。

注册 isHome 状态的目的是改变每个页面的 CSS。

更改路线时如何使用 useEffect 更新状态。 Previously, I would have done this with componentDidUpdate and register prevProps.location.pathname against props.location.pathname , however, my understanding is that this is no longer necessary with the useEffect 钩子。

原文由 Darren 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 768
2 个回答

你想要的效果是“当位置改变时更新我的状态”,这被翻译成 useEffect 代码如下:

   useEffect(() => {
    detectHome();
    return () => {
      detectHome();
    };
  }, [location]);

原文由 Mohamed Ramrami 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您使用的是 react-router,您可以在 useEffect 中订阅位置更改事件:

 import {browserHistory} from 'react-router';

...
useEffect(() => {
  return browserHistory.listen(detectHome);
}, []);
...

这将订阅您的 detectHome 函数以在安装时更改位置并在卸载时取消订阅。

原文由 Alex Gessen 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题