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

Rea*_*ing 71 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;
Run Code Online (Sandbox Code Playgroud)

我需要的是将用途发送到'/ 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>
);
Run Code Online (Sandbox Code Playgroud)

Nou*_*had 52

您可以使用react-router实现此功能withRouter.代码如下:

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);
Run Code Online (Sandbox Code Playgroud)

正如@ambar在评论中提到的,React-router自V4以来已经改变了他们的代码库.这是文件 - 官方,与路由

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

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>
        );
      }
    };
}
Run Code Online (Sandbox Code Playgroud)

如果你已经用redux连接你的组件,并配置了connected-react-router所有你要做的就是 this.props.history.push("/new/url");ie,你不需要withRouterHOC注入history组件道具

  • 似乎“ browserHistory”不再是react-router的一部分。 (3认同)

aar*_*sil 25

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

<span className="input-group-btn">
  <Link to="/login" />Click to login</Link>
</span>
Run Code Online (Sandbox Code Playgroud)

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

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

从升级文档采取这里

您应该已经this.history放置了路由处理程序组件react-router.如果它在routes定义中提到的子组件之下,您可能需要进一步传递它

  • 您也可以在JSX中执行此操作:`{validation && <Link to ="/ login"/>单击以登录</ Link>}`.如果验证为false,则不会呈现任何内容 (3认同)
  • 这是很酷的解决方案,但是我不使用它的原因是因为我需要先进行一种验证,因此需要将其放在一个函数中,例如:```if(true){//重定向到登录}```所以这就是为什么我把它放在一个onClick函数中 (2认同)

jtl*_*sey 18

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

例如,当用户单击链接时<Link to="/" />Click to route</Link>,路由器将查找/并且您可以使用Redirect to并将用户发送到其他位置(如登录路由).

文档ReactRouterTraining:

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

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

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

to:string,重定向到的URL.

<Redirect to="/somewhere/else"/>
Run Code Online (Sandbox Code Playgroud)

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

<Redirect to={{
  pathname: '/login',
  search: '?utm=your+face',
  state: { referrer: currentLocation }
}}/>
Run Code Online (Sandbox Code Playgroud)


Sco*_*ett 17

最简单的网络解决方案!

截至 2020 年,
已确认与以下机构合作:

"react-router-dom": "^5.1.2"
"react": "^16.10.2"
Run Code Online (Sandbox Code Playgroud)

使用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>
  );
}
Run Code Online (Sandbox Code Playgroud)


小智 17

我知道这是一个老问题,但对于 2021 年及之后的任何人来说,React Router V6 useHistory 不再从 React-router-dom 导出,你必须导入 useNavigate。示例代码如下:

import { useNavigate } from "react-router-dom"
Run Code Online (Sandbox Code Playgroud)

在你的反应类或功能组件中:

const navigate = useNavigate()
navigate("/404")
Run Code Online (Sandbox Code Playgroud)


Tom*_*aey 5

对于react-router v2.8.1(可能还有其他2.xx版本,但我尚未对其进行测试),您可以使用此实现来进行Router重定向。

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');
  }
}
Run Code Online (Sandbox Code Playgroud)


Jac*_*bec 5

最简单的解决方案是:

import { Redirect } from 'react-router';

<Redirect to='/componentURL' />
Run Code Online (Sandbox Code Playgroud)