![](/img/trans.png)
[英]Reactjs: React-router-dom Cannot Read Property Push of Undefined
[英]Why am I getting TypeError: Cannot read property 'push' of undefined react-router-dom
我只是在檢查我是否在 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>
);
原因很簡單,正如錯誤所說,您的useHistory
鈎子返回未定義。 發生這種情況是因為此鈎子只能在由Router
包裝的組件內調用,因此決定可能會將其向上移動一級。 看看這個代碼示例https://flaviocopes.com/react-router-uselocation-usehistory-undefined/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.