【发布时间】:2020-01-25 15:52:08
【问题描述】:
我正在寻找一种解决方案来注册路线更改并使用setState 和useEffect 应用新的state。当路由改变时,下面的当前代码不会更新setState 的函数。
例如,我将/ 的pathname 注册到createContext 内的location.pathname === '/',如果pathname 是/,则isHome 的setState 注册了true,但是如果pathname 是/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>
);
};
如果我在pathname / 上console.log(state.isHome) 我得到true,我得到false 的任何其他路径名,但是,如果我改变路线,当前的isHome 状态保持以前状态,直到我滚动并useEffect 适用。
注册isHome 状态的目的是改变每页的CSS。
如何在更改路线时使用useEffect 更新状态。以前,我会使用componentDidUpdate 完成此操作,并针对props.location.pathname 注册prevProps.location.pathname,但是,我的理解是useEffect 钩子不再需要这样做。
【问题讨论】:
标签: javascript reactjs react-hooks gatsby