我只是在检查我是否在 redux 商店中有语言。如果有,我会将其保存在我的 localStorage
中,如果没有,我想导航到组件调用 MultiLanguage
。
我使用以下方法使用 history
但它显示 mw 错误。什么显示了 undefined
的推送以及对此的解决方案是什么?
const history = useHistory();
const language = store.getState().languages.selectedLangauge.language;
console.log("language", language);
if (language) {
localStorage.setItem("language", language);
} else {
history.push("/multilanguage");
}
return (
<div className="font-metropolis_regular">
<Router>
<Route path="/" exact component={Selection} />
<Route path="/login" component={Login} />
<Route path="/home" component={Homepage} />
<Route path="/account" component={Account} />
<Route path="/multilanguage" component={MultiLanguage} />
</Router>
</div>
);
答案 0 :(得分:-1)
原因很简单,正如错误所说,您的 useHistory
钩子返回 undefined。发生这种情况是因为此钩子只能在由 Router
包装的组件内调用,因此决定可能会将其向上移动一级。
看看这个代码示例https://flaviocopes.com/react-router-uselocation-usehistory-undefined/