我正在寻找一种解决方案来注册路线更改并state使用setState和应用新的useEffect。下面的当前代码不会更新setState更改路线时的功能。
例如,我注册pathname的/与location.pathname === '/'内createContext,如果pathname是/所述setState的isHome被登记true,但是如果pathname是/page-1 setState被登记false。
在浏览器重新加载,onMount将state使用正确设置,但在路线改变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>
);
};
如果我console.log(state.isHome)在pathname /我得到true,我得到的任何其他路径名false,但是,如果我改变路线,当前isHome状态保持以前的状态,直到我滚动并useEffect应用。
注册isHome状态的目的是改变每页的 CSS。
useEffect更改路线时如何更新状态。以前,我会使用componentDidUpdate并prevProps.location.pathname针对注册props.location.pathname,但是,我的理解是useEffect钩子不再需要这样做。