【问题标题】:React Router history.goBack doesn't work when using <Redirect />使用 <Redirect /> 时 React Router history.goBack 不起作用
【发布时间】:2020-07-12 12:35:56
【问题描述】:

React 应用程序中,我像这样使用Router

let path='/';
if(condition){
   path='/dashboard'
}else if(condition){
   path='/login'
}

<Router>
 <Redirect to={path} />
   <Switch>
      <Route path="/dashboard"><Dashboard /></Route>
      <Route path="/login"><Login /></Route>
    </Switch>
</Router>

这很好用。但我想在每个页面中实现一个Back Button 以沿页面移动。我这样做:

// The login.jsx component
function Post(props) {
  return (
    <div>
      <button type="button" onClick={() => props.history.goBack()}>
        Go back
      </button>
    </div>
  );
}

但我收到此错误:

Uncaught TypeError: Cannot read property 'goBack' of undefined

然后我采用另一种方法。我用useHistory:

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect,
  Link,
  useHistory,
} from "react-router-dom";

// The login.jsx component
function Post(props) {
  let history = useHistory();
  
  return (
    <div>
      <button type="button" onClick={() => history.goBack()}>
        Go back
      </button>
    </div>
  );
}

这一次当我点击Go Back 按钮时,什么都没有发生!

如果我使用&lt;Link/&gt; 执行此过程,它可以正常工作。但是当我使用&lt;Redirect /&gt; 方法时,它不起作用。我的重定向方法有什么替代方法吗?还是有针对当前方法的解决方案?谢谢。

【问题讨论】:

  • useHistory() 的使用方式是正确的,但问题是您必须填充历史堆栈才能使goBack() 工作。如果堆栈中没有任何内容,goBack() 将无处可去。所以你必须首先push你的重定向到路由器历史记录。

标签: javascript reactjs react-router react-router-dom


【解决方案1】:

要包含在历史记录中的重定向,请使用push

<Redirect push to={path} />

More information here from the docs

【讨论】:

    猜你喜欢
    • 2021-03-15
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    相关资源
    最近更新 更多