为什么我会收到 TypeError:无法读取未定义的 react-router-dom 的属性“push”

时间:2021-07-19 11:36:04

标签: javascript reactjs 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>
  );

1 个答案:

答案 0 :(得分:-1)

原因很简单,正如错误所说,您的 useHistory 钩子返回 undefined。发生这种情况是因为此钩子只能在由 Router 包装的组件内调用,因此决定可能会将其向上移动一级。 看看这个代码示例https://flaviocopes.com/react-router-uselocation-usehistory-undefined/