我正在寻找一种解决方案来注册路由更改并应用新的 state
使用 setState
和 useEffect
。当路由更改时,下面的当前代码不会更新 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 许可协议
你想要的效果是“当位置改变时更新我的状态”,这被翻译成
useEffect
代码如下: