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

Dar*_*ren 7 javascript reactjs gatsby react-hooks

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

例如,我注册pathname/location.pathname === '/'createContext,如果pathname/所述setStateisHome被登记true,但是如果pathname/page-1 setState被登记false

在浏览器重新加载,onMountstate使用正确设置,但在路线改变Link这个没有。另外,请注意,我正在使用 Gatsby 并在这样做时导入{ Link } from 'gatsby'

创建上下文.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>
  );
};
Run Code Online (Sandbox Code Playgroud)

如果我console.log(state.isHome)pathname /我得到true,我得到的任何其他路径名false,但是,如果我改变路线,当前isHome状态保持以前,直到我滚动并useEffect应用。

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

useEffect更改路线时如何更新状态。以前,我会使用componentDidUpdateprevProps.location.pathname针对注册props.location.pathname,但是,我的理解是useEffect钩子不再需要这样做。

Moh*_*ami 5

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

  useEffect(() => {
    detectHome();
    return () => {
      detectHome();
    };
  }, [location]);
Run Code Online (Sandbox Code Playgroud)