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

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

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

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


当前回答

您还可以在无状态组件中使用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

其他回答

以下是如何使用带有ES6的react router v2.0.0来实现这一点。react路由器已远离mixin。

import React from 'react';

export default class MyComponent extends React.Component {
  navigateToPage = () => {
    this.context.router.push('/my-route')
  };

  render() {
    return (
      <button onClick={this.navigateToPage}>Go!</button>
    );
  }
}

MyComponent.contextTypes = {
  router: React.PropTypes.object.isRequired
}

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);

上面已经提到,我们可以使用useNavigate()在上一次更新React Router V6(不包括useHistory)中导航

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

const myComponent = () => {
  const navigate = useNavigate();
  navigate('my_url');
  ...
}

但我在这里找不到的是调用导航出React组件,就像将redux saga函数中的页面导航到另一个页面。以防万一,如果你有同样的问题,这是我发现的。

在根组件中(我称之为<App/>)

import { useNavigate } from 'react-router-dom';
import useBus from 'use-bus';

const App = () => {
  const navigate = useNavigate();
  useBus('@@ui/navigate', (action) => navigate(action.payload.url), []);
  ...
}

脱离React组件(在我的例子中是redux saga函数)

import { dispatch } from 'use-bus';

dispatch({ type: '@@ui/navigate', payload: { url: '/404' } });

希望有帮助!

如果您碰巧通过react router redux将RR4与redux配对,那么也可以使用react router-redux中的路由操作创建器。

import { push, replace, ... } from 'react-router-redux'

class WrappedComponent extends React.Component {
  handleRedirect(url, replaceState = true) {
    replaceState
      ? this.props.dispatch(replace(url))
      : this.props.dispatch(push(url))
  }
  render() { ... }
}

export default connect(null)(WrappedComponent)

如果您使用redux thunk/saga来管理异步流,请在redux操作中导入上述操作创建者,并使用mapDispatchToProps连接到React组件可能会更好。

仅使用浏览器api,独立于任何库

const navigate = (to) => {
    window.history.pushState({}, ",", to);
  };

这不会导致整页刷新。您仍然可以使用浏览器后退按钮