反应钩子:'无法读取未定义的属性'push''

时间:2021-07-13 10:25:16

标签: reactjs react-redux react-hooks

我正在尝试根据 redux 状态将我的主页重定向到“/call”页面。我可以通过手动输入 url 来访问该组件,但不能使用函数来完成。我尝试了“重定向到”、“history.push”,但没有一个对我有用。我无法解决问题。这是我的代码;

const Phone = ({ hidden, photoOpened, inCall }) => {
  const dispatch = useDispatch(getContacts());
  let history = useHistory();

  useEffect(() => {
    if (inCall.inCall) {
      history.push('/call')
    }
  }, [inCall]);

  useEffect(() => {
    dispatch(getContacts());
  }, [])

  return (
    <div hidden={process.env.NODE_ENV === 'development' ? !hidden : hidden} className={photoOpened ? "phone-container-rotate" : "phone-container"}>
      <div className="coque" />
      <Suspense fallback={<div className="animated fadeIn pt-1 text-center">Loading...</div>}>
        <HashRouter basename="/phone">
          <div
            className="phone-content"
            style={{ backgroundImage: `url(${background})` }}
          >
            <HeaderBar />
            <BannerNotifications />
            <Switch>
              {routes.map((route, idx) => {
                return route.component ? (
                  <Route
                    key={idx}
                    path={route.path}
                    exact={route.exact}
                    render={props => <route.component {...props} />}
                  />
                ) : null;
              })}
            </Switch>
          </div>
          <Route component={BottomPhoneNavigator} />
        </HashRouter>
      </Suspense>
    </div>
  );
};

2 个答案:

答案 0 :(得分:3)

您可以尝试在效果中测试历史是否存在,也可以将其添加到依赖项列表中

lst = []
for i in lastNodes:
    if lastNodes.count(i) == 3:
        lst.append(i)```

重要的是,您使用此钩子的组件必须在 useEffect(() => { if (history && inCall.inCall) { history.push('/call') } }, [inCall, history]); 内,我看到您正在使用 Router 但作为使用此钩子的组件的子级。

此外,如果您坚持使用这种结构,为什么不尝试在 Switch 中使用 HashRouter?这可以与一些智能测试一起使用,这样你就不会陷入循环:)

答案 1 :(得分:1)

要使用历史记录,您的电话组件应位于路由器组件内