【问题标题】:Trying to redirect in react using react router尝试使用反应路由器在反应中重定向
【发布时间】:2020-10-20 04:24:50
【问题描述】:

所以我有一个似乎无法解决的错误。目前我正在使用 react 和 react 路由器,但是我似乎无法响应重定向到页面。这是我的代码中的专家(请记住,这是一个功能组件)

<Route path="/login">
  <Login
    onSubmit={(user) => {
      login(user, (status) => {
        if (status == 200) {
          history.push('/home');
        } else {
          history.push('/login');
        }
      });
    }}
  />
</Route>

(作为参考,我有一个登录组件,它接受 onSubmit 回调,并在其中调用预定义的登录方法来检查后端响应的状态并相应地重定向)

当我运行此代码并重定向时,我收到一条错误提示

Unhandled Rejection (TypeError): Cannot read property 'push' of undefined

为了清楚起见,我在组件的前几行中定义了历史

let history = useHistory();

任何帮助将不胜感激!

【问题讨论】:

  • 你创建了路由器吗?什么地方?
  • 是的,这只是我代码的一个小sn-p(实际代码很大程度上与我的问题无关,我不想发布那么多)

标签: javascript reactjs react-tsx


【解决方案1】:

history 解析为undefined,因此您尝试调用undefined.push('path'),因此出现错误。您需要使history 在组件范围内可访问,如下所示:

import {useHistory} from 'react-router-dom'

const App = () => (
const history = useHistory()
return <Login onSubmit={() => history.push('/path')} />
)

【讨论】:

  • 这对我有用!我在我的登录组件中创建了一个 useHistory 实例,并将其传递给我的回调。非常感谢您的回答!
【解决方案2】:

您可以从react-router-dom 使用Redirect

import {  Redirect } from "react-router-dom";

...

<Route path="/login">
  <Login
    onSubmit={(user) => {
      login(user, (status) => {
        if (status == 200) {
           return <Redirect to="/home" />
        } else {
          return <Redirect to="/login" />
        }
      });
    }}
  />
</Route>

【讨论】:

  • 是的,我试过了,但它没有用,Eslint 抛出错误......我开始怀疑我是否正确使用路由器,因为我能找到的所有研究都告诉我使用历史.push 或重定向组件。感谢您的回复!
  • @AkshatAdsule 你试过在&lt;Route path="/login" component={Login}/&gt; 中传递Login 组件
  • 我可以传入 component={} 吗?
  • 否那行不通,您需要在其中传递您的组件,或者您可以使用route 的render 选项
猜你喜欢
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 2020-10-06
  • 2019-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-13
相关资源
最近更新 更多