首页 文章

使用react路由器以编程方式导航

提问于
浏览
887

使用 react-router 我可以使用 Link 元素创建由反应路由器本机处理的链接 .

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

我想进行导航,但不是从链接,例如下拉选择 . 我怎么能在代码中这样做?什么是 this.context

我看到了 Navigation mixin,但我可以不用mixins吗?

26 回答

  • 4

    可能不是最好的方法但是......使用react-router v4,下面的Typescript可以给出一些想法 .

    在下面的渲染组件中,例如 LoginPagerouter 对象是可访问的,只需调用 router.transitionTo('/homepage') 即可导航 .

    导航代码取自https://react-router.now.sh/Match .

    "react-router": "^4.0.0-2", "react": "^15.3.1",

    import Router from 'react-router/BrowserRouter';
    import { History } from 'react-history/BrowserHistory';
    import createHistory from 'history/createBrowserHistory';
    const history = createHistory();
    
    interface MatchWithPropsInterface {
      component: typeof React.Component,
      router: Router,
      history: History,
      exactly?: any,
      pattern: string
    }
    
    class MatchWithProps extends React.Component<MatchWithPropsInterface,any> {
      render() {
        return(
          <Match {...this.props} render={(matchProps) => (
                 React.createElement(this.props.component, this.props)
    
            )}
           />
        )
      }
    }
    
    ReactDOM.render(
        <Router>
          {({ router }) => (
            <div>
              <MatchWithProps exactly pattern="/" component={LoginPage} router={router} history={history} />
              <MatchWithProps pattern="/login" component={LoginPage} router={router} history={history} />
              <MatchWithProps pattern="/homepage" component={HomePage} router={router} history={history} />
              <Miss component={NotFoundView} />
            </div>
          )}
        </Router>,
    
       document.getElementById('app')
    );
    
  • 476

    React Router V4

    TL:博士;

    if (navigate) {
      return <Redirect to="/" push={true} />
    }
    

    The simple and declarative answer is that you need to use <Redirect to= push= /> in combination with setState()

    push:boolean - 当为true时,重定向会将新条目推送到历史记录而不是替换当前条目 .


    import { Redirect } from 'react-router'
    
    class FooBar extends React.Component {
      state = {
        navigate: false
      }
    
      render() {
        const { navigate } = this.state
    
        // here is the important part
        if (navigate) {
          return <Redirect to="/" push={true} />
        }
       // ^^^^^^^^^^^^^^^^^^^^^^^
    
        return (
          <div>
            <button onClick={() => this.setState({ navigate: true })}>
              Home
            </button>
          </div>
        )
      }
    }
    

    完整示例here . 阅读更多here .

    PS . 该示例使用ES7+ Property Initializers初始化状态 . 如果您有兴趣,请查看here .

  • 41

    如果您使用哈希或浏览器历史记录,那么您可以这样做

    hashHistory.push('/login');
    browserHistory.push('/login');
    
  • 28

    也许不是最好的解决方案,但它完成了工作:

    import { Link } from 'react-router-dom';
    
    // create functional component Post
    export default Post = () => (
        <div className="component post">
    
            <button className="button delete-post" onClick={() => {
                // ... delete post
                // then redirect, without page reload, by triggering a hidden Link
                document.querySelector('.trigger.go-home').click();
            }}>Delete Post</button>
    
            <Link to="/" className="trigger go-home hidden"></Link>
    
        </div>
    );
    

    基本上,绑定到一个操作的逻辑(在这种情况下是删除后)将最终调用重定向的触发器 . 这并不理想,因为您将向标记添加DOM节点“触发器”,以便您可以在需要时方便地调用它 . 此外,您将直接与DOM进行交互,这可能不需要在React组件中 .

    但是,通常不需要这种类型的重定向 . 因此,组件标记中的一个或两个额外的隐藏链接不会对此造成太大影响,特别是如果您给它们提供有意义的名称 .

  • 22

    只需使用 this.props.history.push('/where/to/go');

  • 19

    在撰写本文时,正确的答案对我而言

    this.context.router.history.push('/');
    

    但是您需要将PropTypes添加到组件中

    Header.contextTypes = {
      router: PropTypes.object.isRequired
    }
    export default Header;
    

    不要忘记导入PropTypes

    import PropTypes from 'prop-types';
    
  • 18

    React-Router 4.0.0答案

    在4.0及更高版本中,使用历史记录作为组件的支柱 .

    class Example extends React.Component {
       // use `this.props.history.push('/some/path')` here
    };
    

    React-Router 3.0.0答案

    在3.0及以上版本中,使用路由器作为组件的支柱 .

    class Example extends React.Component {
       // use `this.props.router.push('/some/path')` here
    };
    

    React-Router 2.4.0答案

    在2.4及更高版本中,使用更高阶的组件将路由器作为组件的支柱 .

    import { withRouter } from 'react-router';
    
    class Example extends React.Component {
       // use `this.props.router.push('/some/path')` here
    };
    
    // Export the decorated class
    var DecoratedExample = withRouter(Example);
    
    // PropTypes
    Example.propTypes = {
      router: React.PropTypes.shape({
        push: React.PropTypes.func.isRequired
      }).isRequired
    };
    

    React-Router 2.0.0答案

    此版本向后兼容1.x,因此无需升级指南 . 只是通过这些例子应该足够好了 .

    也就是说,如果你想切换到新的模式,路由器内部就有一个browserHistory模块可以访问

    import { browserHistory } from 'react-router'

    现在您可以访问您的浏览器历史记录,因此您可以执行诸如推送,替换等操作...喜欢:

    browserHistory.push('/some/path')

    进一步阅读:HistoriesNavigation


    React-Router 1.x.x答案

    我不打算升级细节 . 您可以在Upgrade Guide中阅读相关内容

    这里问题的主要变化是从导航mixin到History的变化 . 现在它正在使用浏览器historyAPI来改变路由,所以从现在开始我们将使用 pushState() .

    这是使用Mixin的例子:

    var Example = React.createClass({
      mixins: [ History ],
      navigateToHelpPage () {
        this.history.pushState(null, `/help`);
      }
    })
    

    请注意, History 来自rackt/history项目 . 不是来自React-Router本身 .

    如果您由于某种原因不想使用Mixin(可能是因为ES6类),那么您可以从 this.props.history 访问从路由器获得的历史记录 . 它只能由路由器呈现的组件访问 . 因此,如果要在任何子组件中使用它,则需要通过 props 作为属性向下传递 .

    您可以在他们的1.0.x documentation上阅读有关新版本的更多信息 .

    这是a help page specifically about navigating outside your component

    它建议抓取引用 history = createHistory() 并在其上调用 replaceState .

    React-Router 0.13.x答案

    我遇到了同样的问题,只能通过react-router附带的Navigation mixin找到解决方案 .

    这是我如何做到的

    import React from 'react';
    import {Navigation} from 'react-router';
    
    let Authentication = React.createClass({
      mixins: [Navigation],
    
      handleClick(e) {
        e.preventDefault();
    
        this.transitionTo('/');
      },
    
      render(){
        return (<div onClick={this.handleClick}>Click me!</div>);
      }
    });
    

    我无需访问 .context 即可调用 transitionTo()

    或者你可以尝试花哨的ES6 class

    import React from 'react';
    
    export default class Authentication extends React.Component {
      constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
      }
    
      handleClick(e) {
        e.preventDefault();
    
        this.context.router.transitionTo('/');
      }
    
      render(){
        return (<div onClick={this.handleClick}>Click me!</div>);
      }
    }
    
    Authentication.contextTypes = {
      router: React.PropTypes.func.isRequired
    };
    

    React-Router-Redux注意:如果您正在使用Redux,还有另一个名为React-Router-Redux的项目,它为ReactRouter提供了redux绑定,使用了与React-Redux相同的方法 .

    React-Router-Redux有一些可用的方法,允许从内部动作创建者进行简单的导航 . 这些对于在React Native中具有现有体系结构的人来说特别有用,并且他们希望在React Web中使用相同的模式,并且具有最小的样板开销 .

    探索以下方法:

    • push(location)

    • replace(location)

    • go(number)

    • goBack()

    • goForward()

    以下是Redux-Thunk的示例用法:

    ./actioncreators.js

    import { goBack } from 'react-router-redux'
    
    export const onBackPress = () => (dispatch) => dispatch(goBack())
    

    ./viewcomponent.js

    <button
      disabled={submitting}
      className="cancel_button"
      onClick={(e) => {
        e.preventDefault()
        this.props.onBackPress()
      }}
    >
      CANCEL
    </button>
    
  • 15

    以下是使用react-router v2.0.0ES6执行此操作的方法 . react-router 已经离开了mixins .

    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
    }
    
  • 15

    在React-Router v4和ES6中

    您可以使用 withRouterthis.props.history.push .

    import {withRouter} from 'react-router-dom';
    
    class Home extends Component {
    
        componentDidMount() {
            this.props.history.push('/redirect-to');
        }
    }
    
    export default withRouter(Home);
    
  • 8

    React-Router V4

    如果您使用的是版本4,那么您可以使用我的版本库(无耻的插件),您只需发送一个动作,一切正常!

    dispatch(navigateTo("/aboutUs"));
    

    https://www.npmjs.com/package/trippler

  • 6

    那些在react-router v4上实现这个问题的人 . 这是一个工作解决方案,用于从redux操作中导航react应用程序 .

    history.js

    import createHistory from 'history/createBrowserHistory'
    
    export default createHistory()
    

    App.js / Route.jsx

    import { Router, Route } from 'react-router-dom'
    import history from './history'
    ...
    <Router history={history}>
     <Route path="/test" component={Test}/>
    </Router>
    

    another_file.js / redux文件

    import history from './history' 
    
    history.push('/test') // this should change the url and re-render Test component
    

    感谢这个评论:https://github.com/ReactTraining/react-router/issues/3498#issuecomment-301057248

  • 2

    在反应路由器v4中 . 我按照这两种方式以编程方式进行路由 .

    1. this.props.history.push("/something/something")
    2. this.props.history.replace("/something/something")
    

    第二

    替换历史堆栈上的当前条目

    要获取道具的历史记录,您可能必须使用包装

    withRouter https://reacttraining.com/react-router/core/api/withRouter

  • 2

    请查看下面的工作代码:如this article中所述,使用react Router进行导航是一种非常简单的方法:

    class Register extends React.Component {
      state = {
        toDashboard: false,
      }
      handleSubmit = (user) => {
        saveUser(user)
          .then(() => this.setState(() => ({
            toDashboard: true
          })))
      }
      render() {
        if (this.state.toDashboard === true) {
          return <Redirect to='/dashboard' />
        }
    
        return (
          <div>
            <h1>Register</h1>
            <Form onSubmit={this.handleSubmit} />
          </div>
        )
      }
    }
    

    < Redirect />是

    可组合✅声明性✅用户事件 - >状态更改 - >重新渲染✅

    Register component is being rendered by React Router, our code could look like this

    class Register extends React.Component {
      handleSubmit = (user) => {
        saveUser(user).then(() =>
          this.props.history.push('/dashboard')
        ))
      }
      render() {
        return (
          <div>
            <h1>Register</h1>
            <Form onSubmit={this.handleSubmit} />
          </div>
        )
      }
    }
    

    by adding withRouter, it would look like this

    import {
      withRouter
    } from 'react-router-dom'
    
    class Register extends React.Component {
      handleSubmit = (user) => {
        saveUser(user).then(() =>
          this.props.history.push('/dashboard')
        ))
      }
      render() {
        return (
          <div>
            <h1>Register</h1>
            <Form onSubmit={this.handleSubmit} />
          </div>
        )
      }
    }
    
    export default withRouter(Register)
    

    There are two ways to programmatically navigate with React Router - and history.push. Which you use is mostly up to you and your specific use case, though I try to favor Redirect.

  • -2

    如果恰好通过react-router-redux配对RR4 w / 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钩子来反应组件可能会更好 .

  • 26

    使用当前的React版本(15.3), this.props.history.push('/location'); 为我工作,但它显示以下警告:

    browser.js:49警告:[react-router] props.history和context.history已弃用 . 请使用context.router .

    我用_185765这样解决了这个问题:

    import React from 'react';
    
    class MyComponent extends React.Component {
    
        constructor(props) {
            super(props);
            this.backPressed = this.backPressed.bind(this);
        }
    
        backPressed() {
            this.context.router.push('/back-location');
        }
    
        ...
    }
    
    MyComponent.contextTypes = {
        router: React.PropTypes.object.isRequired
    };
    
    export default MyComponent;
    
  • 753

    随着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是一个显示how to use/update react-router的示例应用程序,它包含导航应用程序的示例功能测试 .

  • 12

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

    你也可以不用mixin来做到这一点 .

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

    上下文的问题是除非你在类上定义 contextTypes ,否则它是不可访问的 .

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

  • 10

    对于ES6 React组件,以下解决方案适用于我 .

    我跟着Felippe skinner,但添加了一个端到端的解决方案,以帮助像我这样的初学者 .

    以下是我使用的版本:

    “react-router”:“^ 2.7.0”“反应”:“^ 15.3.1”

    下面是我的反应组件,我使用react-router进行编程导航:

    import React from 'react';
    
    class loginComp extends React.Component {
       constructor( context) {
        super(context);
        this.state = {
          uname: '',
          pwd: ''
        };
      }
    
      redirectToMainPage(){
            this.context.router.replace('/home');
      }
    
      render(){
        return <div>
               // skipping html code 
                 <button onClick={this.redirectToMainPage.bind(this)}>Redirect</button>
        </div>;
      }
    };
    
     loginComp.contextTypes = {
        router: React.PropTypes.object.isRequired
     }
    
     module.exports = loginComp;
    

    Below is the configuration for my router:

    import { Router, Route, IndexRedirect, browserHistory } from 'react-router'
    
     render(<Router history={browserHistory}>
              <Route path='/' component={ParentComp}>
                <IndexRedirect to = "/login"/>
                <Route path='/login' component={LoginComp}/>
                <Route path='/home' component={HomeComp}/>
                <Route path='/repair' component={RepairJobComp} />
                <Route path='/service' component={ServiceJobComp} />
              </Route>
            </Router>, document.getElementById('root'));
    
  • 726

    要以编程方式进行导航,您需要将新的 history 推送到 component 中的 props.history ,这样这样的事情可以为您完成工作:

    //using ES6
    import React from 'react';
    
    class App extends React.Component {
    
      constructor(props) {
        super(props)
        this.handleClick = this.handleClick.bind(this)
      }
    
      handleClick(e) {
        e.preventDefault()
        /* Look at here, you can add it here */
        this.props.history.push('/redirected');
      }
    
      render() {
        return (
          <div>
            <button onClick={this.handleClick}>
              Redirect!!!
            </button>
          </div>
        )
      }
    }
    
    export default App;
    
  • 3

    React-Router v2

    对于最新版本( v2.0.0-rc5 ),推荐的导航方法是直接推送历史单例 . 你可以在Navigating outside of Components doc中看到这一点 .

    相关摘录:

    import { browserHistory } from 'react-router';
    browserHistory.push('/some/path');
    

    如果使用较新的react-router API,则需要在组件内部使用 history this.props ,这样:

    this.props.history.push('/some/path');
    

    它还提供 pushState ,但每个已记录的警告已弃用 .

    如果使用 react-router-redux ,它提供了一个 push 函数,您可以这样调度:

    import { push } from 'react-router-redux';
    this.props.dispatch(push('/some/path'));
    

    但是,这可能仅用于更改URL,而不是实际导航到页面 .

  • 14

    在事情正常之前,我尝试过至少10种方法!

    @Felipe Skinner的 withRouter 答案对我来说有点压倒性的,我不确定我是否想制作新的"ExportedWithRouter"类名 .

    这是最简单,最干净的方法,大约是当前的React-Router 3.0.0和ES6:

    带有ES6的React-Router 3.x.x:

    import { withRouter } from 'react-router';
    
    class Example extends React.Component {
       // use `this.props.router.push('/some/path')` here
    };
    
    // Export the decorated class
    export default withRouter(Example);
    

    或者,如果它不是您的默认类,则导出如下:

    withRouter(Example);
    export { Example };
    

    请注意,在3.x.x中, <Link> 组件本身正在使用 router.push ,因此您可以传递任何您传递 <Link to= 标记的内容,例如:

    this.props.router.push({pathname: '/some/path', query: {key1: 'val1', key2: 'val2'})'
    
  • 6

    React-Router 4.x答案:

    在我的结尾,我喜欢有一个历史对象,我甚至可以携带外部组件 . 我喜欢做的是拥有一个我按需导入的单个history.js文件,并且只是操作它 .

    您只需将 BrowserRouter 更改为路由器,并指定历史记录道具 . 这不会改变任何事情,除非你有自己的历史对象,你可以根据需要进行操作 .

    您需要安装historyreact-router 使用的库 .

    示例用法,ES6表示法:

    history.js

    import createBrowserHistory from 'history/createBrowserHistory'
    export default createBrowserHistory()
    

    BasicComponent.js

    import React, { Component } from 'react';
    import history from './history';
    
    class BasicComponent extends Component {
    
        goToIndex(e){
            e.preventDefault();
            history.push('/');
        }
    
        render(){
            return <a href="#" onClick={this.goToIndex}>Previous</a>;
        }
    }
    

    编辑2018年4月16日:

    如果必须从实际从 Route 组件呈现的组件导航,您还可以从props访问历史记录,如下所示:

    BasicComponent.js

    import React, { Component } from 'react';
    
    class BasicComponent extends Component {
    
        navigate(e){
            e.preventDefault();
            this.props.history.push('/url');
        }
    
        render(){
            return <a href="#" onClick={this.navigate}>Previous</a>;
        }
    }
    
  • 6

    根据以前的答案
    来自JoséAntonioPostigo和Ben Wheeler
    新奇?将写于 Typescript
    和使用 decorators
    static property / field

    import * as React from "react";
    import Component = React.Component;
    import { withRouter } from "react-router";
    
    export interface INavigatorProps {
        router?: ReactRouter.History.History;
    }
    
    /**
     * Note: goes great with mobx 
     * @inject("something") @withRouter @observer
     */
    @withRouter
    export class Navigator extends Component<INavigatorProps, {}>{
        navigate: (to: string) => void;
        constructor(props: INavigatorProps) {
            super(props);
            let self = this;
            this.navigate = (to) => self.props.router.push(to);
        }
        render() {
            return (
                <ul>
                    <li onClick={() => this.navigate("/home")}>
                        Home
                    </li>
                    <li onClick={() => this.navigate("/about")}>
                        About
                    </li>
                </ul>
            )
        }
    }
    
    /**
     * Non decorated 
     */
    export class Navigator2 extends Component<INavigatorProps, {}> {
    
        static contextTypes = {
            router: React.PropTypes.object.isRequired,
        };
    
        navigate: (to: string) => void;
        constructor(props: INavigatorProps, context: any) {
            super(props, context);
            let s = this;
            this.navigate = (to) =>
                s.context.router.push(to);
        }
        render() {
            return (
                <ul>
                    <li onClick={() => this.navigate("/home")}>
                        Home
                    </li>
                    <li onClick={() => this.navigate("/about")}>
                        About
                    </li>
                </ul>
            )
        }
    }
    

    无论今天安装什么npm . "react-router":"^3.0.0"和
    "@types/react-router":"^2.0.41"

  • 0

    React Router v4

    使用React Router的v4,您可以采用三种方法在组件内进行编程路由 .

    • 使用 withRouter 高阶组件 .

    • 使用合成并渲染 <Route>

    • 使用 context .

    React Router主要是history库的包装器 . history 通过浏览器和哈希历史记录处理与浏览器window.history的交互 . 它还提供了一个内存历史记录,对于没有全局历史记录的环境非常有用 . 这在移动应用程序开发( react-native )和使用Node进行单元测试时特别有用 .

    history 实例有两种导航方法: pushreplace . 如果您将 history 视为已访问位置的数组, push 将向阵列添加新位置, replace 将使用新位置替换阵列中的当前位置 . 通常,您需要在导航时使用 push 方法 .

    在早期版本的React Router中,您必须创建自己的 history 实例,但在第4版中, <BrowserRouter><HashRouter><MemoryRouter> 组件将为您创建浏览器,哈希和内存实例 . React Router通过 router 对象下的上下文使与您的路由器关联的 history 实例的属性和方法可用 .

    1.使用withRouter高阶组件

    withRouter 高阶组件将注入 history 对象作为组件的prop . 这使您可以访问 pushreplace 方法而无需处理 context .

    import { withRouter } from 'react-router-dom'
    // this also works with react-router-native
    
    const Button = withRouter(({ history }) => (
      <button
        type='button'
        onClick={() => { history.push('/new-location') }}
      >
        Click Me!
      </button>
    ))
    

    2.使用合成并渲染<Route>

    <Route> 组件不仅适用于匹配位置 . 您可以渲染无路径路径 it will always match the current location . <Route> 组件传递与 withRouter 相同的道具,因此您将能够通过 history 道具访问 history 方法 .

    import { Route } from 'react-router-dom'
    
    const Button = () => (
      <Route render={({ history}) => (
        <button
          type='button'
          onClick={() => { history.push('/new-location') }}
        >
          Click Me!
        </button>
      )} />
    )
    

    3.使用上下文*

    *But you probably should not

    最后一个选项是您只有在使用React的context模型时才能使用的选项 . 虽然上下文是一种选择,但应该强调上下文是一个不稳定的API,React在其文档中有一个Why Not To Use Context部分 . 所以使用风险自负!

    const Button = (props, context) => (
      <button
        type='button'
        onClick={() => {
          // context.history.push === history.push
          context.history.push('/new-location')
        }}
      >
        Click Me!
      </button>
    )
    
    // you need to specify the context type so that it
    // is available within the component
    Button.contextTypes = {
      history: React.PropTypes.shape({
        push: React.PropTypes.func.isRequired
      })
    }
    

    1和2是最简单的选择,所以对于大多数用例来说,它们是你最好的选择 .

  • 8

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

    history放入单独的文件(例如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()
      }
    })
    
  • 8

    要将 withRouter 与基于类的组件一起使用,请尝试以下方法 . 不要忘记更改导出语句以使用 withRouter

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

    class YourClass extends React.Component {
      yourFunction = () => {
        doSomeAsyncAction(() =>
          this.props.history.push('/other_location')
        )
      }
    
      render() {
        return (
          <div>
            <Form onSubmit={ this.yourFunction } />
          </div>
        )
      }
    }
    
    export default withRouter(YourClass);
    

相关问题