如何使用react-router重定向到另一条路由?

时间:2016-01-12 04:25:21

标签: javascript reactjs

令人难以置信的是,有关React的每个库的文档有多糟糕。

我正在尝试使用react-router(版本^ 1.0.3 )进行简单重定向到另一个视图,我只是累了。

import React from 'react';
import {Router, Route, Link, RouteHandler} from 'react-router';


class HomeSection extends React.Component {

  static contextTypes = {
    router: PropTypes.func.isRequired
  };

  constructor(props, context) {
    super(props, context);
  }

  handleClick = () => {
    console.log('HERE!', this.contextTypes);
    // this.context.location.transitionTo('login');
  };

  render() {
    return (
      <Grid>
        <Row className="text-center">          
          <Col md={12} xs={12}>
            <div className="input-group">
              <span className="input-group-btn">
                <button onClick={this.handleClick} type="button">
                </button>
              </span>
            </div>
          </Col>
        </Row>
      </Grid>
    );
  }
};

HomeSection.contextTypes = {
  location() {
    React.PropTypes.func.isRequired
  }
}

export default HomeSection;

我需要的是将用途发送到'/ login',就是这样。

我该怎么办?

控制台中出现

错误:

  

未捕获的ReferenceError:未定义PropTypes

带有我的路线的文件

// LIBRARY
/*eslint-disable no-unused-vars*/
import React from 'react';
/*eslint-enable no-unused-vars*/
import {Route, IndexRoute} from 'react-router';

// COMPONENT
import Application from './components/App/App';
import Contact from './components/ContactSection/Contact';
import HomeSection from './components/HomeSection/HomeSection';
import NotFoundSection from './components/NotFoundSection/NotFoundSection';
import TodoSection from './components/TodoSection/TodoSection';
import LoginForm from './components/LoginForm/LoginForm';
import SignupForm from './components/SignupForm/SignupForm';

export default (
    <Route component={Application} path='/'>
      <IndexRoute component={HomeSection} />
      <Route component={HomeSection} path='home' />
      <Route component={TodoSection} path='todo' />
      <Route component={Contact} path='contact' />
      <Route component={LoginForm} path='login' />
      <Route component={SignupForm} path='signup' />
      <Route component={NotFoundSection} path='*' />
    </Route>
);

7 个答案:

答案 0 :(得分:39)

您可以使用react-router BrowserHistory来实现此功能。代码如下:

import React, {Component} from 'react';
import {browserHistory} from 'react-router';

export default class yourComponent extends Component {

    handleClick = () => {
        browserHistory.push('/login');
    };

    render() {
        return (
          <Grid>
            <Row className="text-center">          
              <Col md={12} xs={12}>
                <div className="input-group">
                  <span className="input-group-btn">
                    <button onClick={this.handleClick} type="button">
                    </button>
                  </span>
                </div>
              </Col>
            </Row>
          </Grid>
        );
      }
    };

}

正如@ambar在评论中提到的,React-router已经改变了自V4以来的代码库。以下是文档 - officialwithRouter

对于V4及以上版本,您可以使用withRouter HOC:

import React, {Component} from 'react';
import {withRouter} from "react-router-dom";

class yourComponent extends Component {
    handleClick = () => {
        this.props.history.push("path/to/push");
    }

    render() {
        return (
          <Grid>
            <Row className="text-center">          
              <Col md={12} xs={12}>
                <div className="input-group">
                  <span className="input-group-btn">
                    <button onClick={this.handleClick} type="button"></button>
                  </span>
                </div>
              </Col>
            </Row>
          </Grid>
        );
      }
    };

}

export default withRouter(yourComponent);

如果您已将组件与redux连接,并且已配置react-router-middleware,那么您只需要做 this.props.history.push("/new/url");即,您不需要withRouter HOC将history注入组件道具

答案 1 :(得分:20)

对于简单的答案,您可以使用Link中的react-router组件,而不是button。有一些方法可以改变JS的路线,但似乎你不需要这里。

<span className="input-group-btn">
  <Link to="/login" />Click to login</Link>
</span>

要在1.0.x中以编程方式执行此操作,您可以在clickHandler函数中执行此操作:

this.history.pushState(null, 'login');

取自升级文档here

您应该this.historyreact-router放置在路由处理程序组件上routes。如果它是{{1}}定义中提到的子组件之下,则可能需要将其进一步传递

答案 2 :(得分:15)

  

如何使用react-router重定向到另一条路由?

例如,当用户点击链接<Link to="/" />Click to route</Link> react-router将寻找/并且您可以使用Redirect to并将用户发送到其他地方,例如登录路由。

来自docsReactRouterTraining

  

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

import { Route, Redirect } from 'react-router'

<Route exact path="/" render={() => (
  loggedIn ? (
    <Redirect to="/dashboard"/>
  ) : (
    <PublicHomePage/>
  )
)}/>
  

to:string,重定向到的URL。

<Redirect to="/somewhere/else"/>
  

to:object,重定向到的位置。

<Redirect to={{
  pathname: '/login',
  search: '?utm=your+face',
  state: { referrer: currentLocation }
}}/>

答案 3 :(得分:12)

最简单的网络解决方案!

截至2020年
确认与以下公司合作:

"react-router-dom": "^5.1.2"
"react": "^16.10.2"

使用useHistory()钩子!

import React from 'react';
import { useHistory } from "react-router-dom";


export function HomeSection() {
  const history = useHistory();
  const goLogin = () => history.push('login');

  return (
    <Grid>
      <Row className="text-center">          
        <Col md={12} xs={12}>
          <div className="input-group">
            <span className="input-group-btn">
              <button onClick={goLogin} type="button" />
            </span>
          </div>
        </Col>
      </Row>
    </Grid>
  );
}

答案 4 :(得分:4)

使用react-router v2.8.1(可能还有其他2.x.x版本,但我还没有测试过),您可以使用此实现来进行路由器重定向。

import { Router } from 'react-router';

export default class Foo extends Component {

  static get contextTypes() {
    return {
      router: React.PropTypes.object.isRequired,
    };
  }

  handleClick() {
    this.context.router.push('/some-path');
  }
}

答案 5 :(得分:1)

我知道这是一个老问题,但是对于 2021 年和 React Router V6 之后来到这里的人,useHistory 不再从 react-router-dom 导出,您必须改为导入 useNavigate。示例代码如下:

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

在你的 React 类或功能组件中:

const navigate = useNavigate()
navigate("/404")

答案 6 :(得分:-1)

最简单的解决方案是:

import { Redirect } from 'react-router';

<Redirect to='/componentURL' />