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

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

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

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


当前回答

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

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

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

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

其他回答

React路由器v4和ES6

您可以使用Router和this.props.history.push。

import {withRouter} from 'react-router-dom';

class Home extends Component {

    componentDidMount() {
        this.props.history.push('/redirect-to');
    }
}

export default withRouter(Home);

您还可以在无状态组件中使用useHistory钩子。文档示例:

import { useHistory } from "react-router"

function HomeButton() {
  const history = useHistory()

  return (
    <button type="button" onClick={() => history.push("/home")}>
      Go home
    </button>
  )
}

注意:在中添加了挂钩react-router@5.1.0并且需要反应@>=16.8

对于已经使用React Router v6的用户,可以使用React Router提供的useNavigate钩子来完成。

使用此钩子进行导航非常简单:

import { generatePath, useNavigate } from 'react-router';

navigate(-1); // navigates back
navigate('/my/path'); // navigates to a specific path
navigate(generatePath('my/path/:id', { id: 1 })); // navigates to a dynamic path, generatePath is very useful for url replacements

只需使用useNavigate,即可使用最新版本的react

新文件.js

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

const Newfile = () => {
    const navigate = useNavigate();
   
    ....

    navigate("yourdesiredlocation");

    ....
}

export default Newfile;

在代码中使用上述的useNavigate功能。

对于这一个,谁不控制服务器端,因此使用哈希路由器v2:

将历史记录放入单独的文件(例如app_history.js ES6):

import { useRouterHistory } from 'react-router'
import { createHashHistory } from 'history'
const appHistory = useRouterHistory(createHashHistory)({ queryKey: false });

export default appHistory;

并在任何地方使用它!

react router(app.js ES6)的入口点:

import React from 'react'
import { render } from 'react-dom'
import { Router, Route, Redirect } from 'react-router'
import appHistory from './app_history'
...
const render((
  <Router history={appHistory}>
  ...
  </Router>
), document.querySelector('[data-role="app"]'));

任何组件(ES6)内的导航:

import appHistory from '../app_history'
...
ajaxLogin('/login', (err, data) => {
  if (err) {
    console.error(err); // login failed
  } else {
    // logged in
    appHistory.replace('/dashboard'); // or .push() if you don't need .replace()
  }
})