使用react router,我可以使用Link元素来创建由react route本地处理的链接。

我看到它在内部调用this.context.transitionTo(…)。

我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?

我看到了导航混合,但我可以在没有混合的情况下这样做吗?


当前回答

要将withRouter与基于类的组件一起使用,请尝试以下操作。不要忘记将导出语句更改为与Router一起使用:

从“react router dom”导入{withRouter}

class YourClass extends React.Component {
  yourFunction = () => {
    doSomeAsyncAction(() =>
      this.props.history.push('/other_location')
    )
  }

  render() {
    return (
      <div>
        <Form onSubmit={ this.yourFunction } />
      </div>
    )
  }
}

export default withRouter(YourClass);

其他回答

如果您正在使用哈希或浏览器历史记录,那么您可以

hashHistory.push('/login');
browserHistory.push('/login');

在react router的上下文中,已经有大量的答案可以正确、准确地回答这个问题,但我想花点时间指出一些我在其他答案中没有提到的问题。

这是一种stackoverflow的比喻,建议用与原始问题不同的方式来做一些事情,但在这种情况下,由于问题的年龄,我觉得在当前的时间里,问题的表述会有所不同。

我建议放弃react router,只需通过window.location.href=[yoururlhere]推送到本地浏览器位置,然后通过正则表达式(或确切的)匹配window.location.pathname和您的预期路径来检查路径。

更简单的答案通常是最好的答案,在这种情况下,React Router的用例由本地位置对象API提供更好的服务。

带挂钩的React Router v6

import {useNavigate} from 'react-router-dom';
let navigate = useNavigate();
navigate('home');

为了浏览浏览器历史,

navigate(-1); ---> Go back
navigate(1);  ---> Go forward
navigate(-2); ---> Move two steps backward.

在我的回答中,有三种不同的方法可以通过编程重定向到路由。已经介绍了一些解决方案,但下面的解决方案仅针对具有附加演示应用程序的功能组件。

使用以下版本:

反应:16.13.1反应时间:16.13.1反应路由器:5.2.0反应路由器dom:5.2.0字体:3.7.2

配置:

因此,首先解决方案是使用HashRouter,配置如下:

<HashRouter>
    // ... buttons for redirect

    <Switch>
      <Route exact path="/(|home)" children={Home} />
      <Route exact path="/usehistory" children={UseHistoryResult} />
      <Route exact path="/withrouter" children={WithRouterResult} />
      <Route exact path="/redirectpush" children={RedirectPushResult} />
      <Route children={Home} />
    </Switch>
</HashRouter>

从有关<HashRouter>的文档中:

一个<Router>,它使用URL的哈希部分(即window.location.hash)来保持UI与URL同步。

解决:

使用<Redirect>使用useState推送:

在功能组件(我的存储库中的RedirectPushAction组件)中使用,我们可以使用useState来处理重定向。棘手的是,一旦发生重定向,我们需要将重定向状态设置回false。通过使用带有0延迟的setTimeOut,我们等待React提交重定向到DOM,然后返回按钮,以便下次使用。

请在下面找到我的示例:

const [redirect, setRedirect] = useState(false);
const handleRedirect = useCallback(() => {
    let render = null;
    if (redirect) {
        render = <Redirect to="/redirectpush" push={true} />

        // In order wait until committing to the DOM
        // and get back the button for clicking next time
        setTimeout(() => setRedirect(false), 0);
    }
    return render;
}, [redirect]);

return <>
    {handleRedirect()}
    <button onClick={() => setRedirect(true)}>
        Redirect push
    </button>
</>

从<Redirect>文档:

渲染<重定向>将导航到新位置。新位置将覆盖历史堆栈中的当前位置,就像服务器端重定向(HTTP 3xx)那样。

使用useHistory钩子:

在我的解决方案中,有一个名为UseHistoryAction的组件,它表示以下内容:

let history = useHistory();

return <button onClick={() => { history.push('/usehistory') }}>
    useHistory redirect
</button>

useHistory钩子允许我们访问历史对象,它帮助我们以编程方式导航或更改路线。

使用withRouter,从道具获取历史记录:

创建了一个名为WithRouterAction的组件,显示如下:

const WithRouterAction = (props:any) => {
    const { history } = props;

    return <button onClick={() => { history.push('/withrouter') }}>
        withRouter redirect
    </button>
}

export default withRouter(WithRouterAction);

阅读路由器文档:

您可以通过withRouter高阶组件访问历史对象的财产和最接近的<Route>匹配项。无论何时渲染,withRouter都会将更新的匹配、位置和历史属性传递给包装组件。

演示:

为了更好地表示,我用这些示例构建了一个GitHub存储库,请在下面找到它:

React Router程序化重定向示例

以下是最简单、最干净的方法,大约是当前的React Router 3.0.0和ES6:

使用ES6反应路由器3.x.x:

import { withRouter } from 'react-router';

class Example extends React.Component {
   // use `this.props.router.push('/some/path')` here
};

// Export the decorated class
export default withRouter(Example);

或者,如果不是默认类,则导出如下:

withRouter(Example);
export { Example };

注意,在3.x.x中,<Link>组件本身使用router.push,因此您可以传递任何传递<Linkto=标记的内容,例如:

   this.props.router.push({pathname: '/some/path', query: {key1: 'val1', key2: 'val2'})'