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

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

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

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


当前回答

如果您使用的是更新版本的React,那么使用“useHistory”钩子是最好的选择。

其他回答

对于这一个,谁不控制服务器端,因此使用哈希路由器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()
  }
})

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

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

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

警告:此答案仅涵盖1.0之前的ReactRouter版本之后,我将用1.0.0-rc1用例更新这个答案!

你也可以在没有混合的情况下这样做。

let Authentication = React.createClass({
  contextTypes: {
    router: React.PropTypes.func
  },
  handleClick(e) {
    e.preventDefault();
    this.context.router.transitionTo('/');
  },
  render(){
    return (<div onClick={this.handleClick}>Click me!</div>);
  }
});

有上下文的问题是,除非在类上定义contextType,否则它是不可访问的。

至于什么是上下文,它是一个对象,就像props一样,从父对象传递给子对象,但它是隐式传递的,不需要每次都重新声明props。看见https://www.tildedave.com/2014/11/15/introduction-to-contexts-in-react-js.html

随着React Router v4即将推出,现在有了一种新的实现方式。

import { MemoryRouter, BrowserRouter } from 'react-router';

const navigator = global && global.navigator && global.navigator.userAgent;
const hasWindow = typeof window !== 'undefined';
const isBrowser = typeof navigator !== 'undefined' && navigator.indexOf('Node.js') === -1;
const Router = isBrowser ? BrowserRouter : MemoryRouter;

<Router location="/page-to-go-to"/>

react lego是一个示例应用程序,展示了如何使用/更新react router,它包括导航应用程序的示例功能测试。

在基于类的组件中编程导航。

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

class MyComponent extends React.Component{
    state = {rpath: null}

    const goTo = (path) => this.setState({rpath: path});

    render(){
        if(this.state.rpath){
            return <Redirect to={this.state.rpath}/>
        }
        .....
        .....
    }
}