471

在当前版本的 React Router (v3) 中,我可以接受服务器响应并使用browserHistory.push它转到相应的响应页面。但是,这在 v4 中不可用,我不确定处理此问题的适当方法是什么。

在这个例子中,使用 Redux,components/app-product-form.jsthis.props.addProduct(props)在用户提交表单时调用。当服务器返回成功时,用户被带到购物车页面。

// actions/index.js
export function addProduct(props) {
  return dispatch =>
    axios.post(`${ROOT_URL}/cart`, props, config)
      .then(response => {
        dispatch({ type: types.AUTH_USER });
        localStorage.setItem('token', response.data.token);
        browserHistory.push('/cart'); // no longer in React Router V4
      });
}

如何从 React Router v4 的功能重定向到购物车页面?

4

25 回答 25

395

您可以在history组件之外使用这些方法。通过以下方式尝试。

首先,创建一个history使用历史包的对象:

// src/history.js

import { createBrowserHistory } from 'history';

export default createBrowserHistory();

然后把它包起来<Router>请注意,你应该使用import { Router }而不是import { BrowserRouter as Router }):

// src/index.jsx

// ...
import { Router, Route, Link } from 'react-router-dom';
import history from './history';

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/login">Login</Link></li>
        </ul>
        <Route exact path="/" component={HomePage} />
        <Route path="/login" component={LoginPage} />
      </div>
    </Router>
  </Provider>,
  document.getElementById('root'),
);

从任何地方更改您的当前位置,例如:

// src/actions/userActionCreators.js

// ...
import history from '../history';

export function login(credentials) {
  return function (dispatch) {
    return loginRemotely(credentials)
      .then((response) => {
        // ...
        history.push('/');
      });
  };
}

UPD:你也可以在React Router FAQ中看到一个稍微不同的例子。

于 2017-08-23T21:32:27.263 回答
388

React Router v4 与 v3(及更早版本)根本不同,你不能browserHistory.push()像以前那样做。

如果您想了解更多信息,此讨论似乎相关:

  • 创建一个新的browserHistory将不起作用,因为<BrowserRouter>创建了它自己的历史实例,并监听它的变化。因此,不同的实例将更改 url 但不会更新<BrowserRouter>.
  • browserHistory在 v4 中没有被 react-router 公开,仅在 v2 中。

相反,您有几个选项可以执行此操作:

  • 使用withRouter高阶组件

    相反,您应该使用withRouter高阶组件,并将其包装到将推送到历史记录的组件中。例如:

    import React from "react";
    import { withRouter } from "react-router-dom";
    
    class MyComponent extends React.Component {
      ...
      myFunction() {
        this.props.history.push("/some/Path");
      }
      ...
    }
    export default withRouter(MyComponent);
    

    查看官方文档了解更多信息:

    您可以通过 withRouter 高阶组件访问history对象的属性和最近的属性<Route>match每次路由使用与<Route>render props:相同的 props 更改时,withRouter 都会重新渲染其组件{ match, location, history }


  • 使用contextAPI

    使用上下文可能是最简单的解决方案之一,但作为实验性 API,它不稳定且不受支持。只有在其他一切都失败时才使用它。这是一个例子:

    import React from "react";
    import PropTypes from "prop-types";
    
    class MyComponent extends React.Component {
      static contextTypes = {
        router: PropTypes.object
      }
      constructor(props, context) {
         super(props, context);
      }
      ...
      myFunction() {
        this.context.router.history.push("/some/Path");
      }
      ...
    }
    

    查看有关上下文的官方文档:

    如果您希望您的应用程序稳定,请不要使用上下文。它是一个实验性 API,很可能会在未来的 React 版本中中断。

    如果您不顾这些警告仍坚持使用上下文,请尝试将您对上下文的使用隔离到一个小区域,并尽可能避免直接使用上下文 API,以便在 API 更改时更容易升级。

于 2017-03-10T10:26:29.987 回答
115

现在使用 react-router v5,您可以像这样使用 useHistory 钩子:

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

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

阅读更多:https ://reacttraining.com/react-router/web/api/Hooks/usehistory

于 2019-10-24T07:59:53.740 回答
39

React Router 4 中最简单的方法是使用

this.props.history.push('/new/url');

但是要使用这种方法,您现有的组件应该可以访问history对象。我们可以通过

  1. 如果您的组件Route直接链接到,那么您的组件已经可以访问history对象。

    例如:

    <Route path="/profile" component={ViewProfile}/>
    

    这里ViewProfile可以访问history

  2. 如果没有Route直接连接。

    例如:

    <Route path="/users" render={() => <ViewUsers/>}
    

    然后我们必须使用withRouter高阶函数来扭曲现有组件。

    内部 ViewUsers组件

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

    • export default withRouter(ViewUsers);

    现在就是这样,您的ViewUsers组件可以访问history对象。

更新

2- 在这种情况下,将所有路由传递props给您的组件,然后this.props.history即使没有HOC

例如:

<Route path="/users" render={props => <ViewUsers {...props} />}
于 2018-12-24T18:13:50.117 回答
27

我是这样做的:

import React, {Component} from 'react';

export default class Link extends Component {
    constructor(props) {
        super(props);
        this.onLogout = this.onLogout.bind(this);
    }
    onLogout() {
        this.props.history.push('/');
    }
    render() {
        return (
            <div>
                <h1>Your Links</h1>
                <button onClick={this.onLogout}>Logout</button>
            </div>
        );
    }
}

用于this.props.history.push('/cart');重定向到购物车页面,它将被保存在历史对象中。

享受吧,迈克尔。

于 2017-04-12T21:03:07.783 回答
23

根据React Router v4 文档 - Redux Deep Integration session

深度集成需要:

“能够通过调度操作进行导航”

但是,他们推荐这种方法作为“深度集成”的替代方案:

“您可以传递提供的历史对象以将组件路由到您的操作并在那里导航,而不是调度操作来导航。”

所以你可以用 withRouter 高阶组件包装你的组件:

export default withRouter(connect(null, { actionCreatorName })(ReactComponent));

这会将历史 API 传递给道具。因此,您可以调用将历史作为参数传递的动作创建者。例如,在您的 ReactComponent 内部:

onClick={() => {
  this.props.actionCreatorName(
    this.props.history,
    otherParams
  );
}}

然后,在您的操作/index.js 中:

export function actionCreatorName(history, param) {
  return dispatch => {
    dispatch({
      type: SOME_ACTION,
      payload: param.data
    });
    history.push("/path");
  };
}
于 2017-08-13T23:51:43.550 回答
19

讨厌的问题,花了我很多时间,但最终,我以这种方式解决了它:

用函数包装容器withRouter并将历史记录传递给您的操作 mapDispatchToProps。在行动中使用 history.push('/url') 进行导航。

行动:

export function saveData(history, data) {
  fetch.post('/save', data)
     .then((response) => {
       ...
       history.push('/url');
     })
};

容器:

import { withRouter } from 'react-router-dom';
...
const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    save: (data) => dispatch(saveData(ownProps.history, data))}
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Container));

这对React Router v4.x有效。

于 2017-10-28T23:06:55.303 回答
9

我提供了另一种解决方案,以防它对其他人有价值。

我有一个history.js文件,其中包含以下内容:

import createHistory from 'history/createBrowserHistory'
const history = createHistory()
history.pushLater = (...args) => setImmediate(() => history.push(...args))
export default history

接下来,在我定义路由器的根上,我使用以下内容:

import history from '../history'
import { Provider } from 'react-redux'
import { Router, Route, Switch } from 'react-router-dom'

export default class Root extends React.Component {
  render() {
    return (
     <Provider store={store}>
      <Router history={history}>
       <Switch>
        ...
       </Switch>
      </Router>
     </Provider>
    )
   }
  }

最后,在我actions.js导入 History 并使用 pushLater

import history from './history'
export const login = createAction(
...
history.pushLater({ pathname: PATH_REDIRECT_LOGIN })
...)

这样,我可以在 API 调用后推送新的操作。

希望能帮助到你!

于 2017-10-30T12:15:55.167 回答
7

小心不要使用react-router@5.2.0or react-router-dom@5.2.0with history@5.0.0。URL 将在history.push或任何其他推送到历史说明之后更新,但导航无法使用react-router。用于npm install history@4.10.1更改历史版本。请参阅升级到 v 5 后 React 路由器不工作

我认为当推动历史发生时,这个问题就会发生。例如<NavLink to="/apps">在 NavLink.js 中使用面临一个消耗<RouterContext.Consumer>. context.location当推送到历史时,正在更改为具有操作和位置属性的对象。currentLocation.pathname与路径匹配的 null 也是如此。

于 2021-01-02T10:17:40.493 回答
7

this.context.history.push不管用。

我设法让 push 像这样工作:

static contextTypes = {
    router: PropTypes.object
}

handleSubmit(e) {
    e.preventDefault();

    if (this.props.auth.success) {
        this.context.router.history.push("/some/Path")
    }

}
于 2017-05-18T08:25:29.077 回答
6

在这种情况下,您将道具传递给您的 thunk。所以你可以简单地打电话

props.history.push('/cart')

如果不是这种情况,您仍然可以从组件传递历史记录

export function addProduct(data, history) {
  return dispatch => {
    axios.post('/url', data).then((response) => {
      dispatch({ type: types.AUTH_USER })
      history.push('/cart')
    })
  }
}
于 2017-08-09T09:04:59.677 回答
5

我在同一个话题上挣扎。我正在使用 react-router-dom 5、Redux 4 和 BrowserRouter。我更喜欢基于函数的组件和钩子。

你像这样定义你的组件

import { useHistory } from "react-router-dom";
import { useDispatch } from "react-redux";

const Component = () => {
  ...
  const history = useHistory();
  dispatch(myActionCreator(otherValues, history));
};

您的动作创建者正在关注

const myActionCreator = (otherValues, history) => async (dispatch) => {
  ...
  history.push("/path");
}

如果不需要异步,您当然可以使用更简单的操作创建器

于 2020-12-13T12:52:17.300 回答
4

如果您使用的是 Redux,那么我建议您使用 npm package react-router-redux。它允许您调度 Redux 商店导航操作。

您必须按照他们的自述文件中的描述创建商店。

最简单的用例:

import { push } from 'react-router-redux'

this.props.dispatch(push('/second page'));

容器/组件的第二个用例:

容器:

import { connect } from 'react-redux';
import { push } from 'react-router-redux';

import Form from '../components/Form';

const mapDispatchToProps = dispatch => ({
  changeUrl: url => dispatch(push(url)),
});

export default connect(null, mapDispatchToProps)(Form);

零件:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export default class Form extends Component {
  handleClick = () => {
    this.props.changeUrl('/secondPage');
  };

  render() {
    return (
      <div>
        <button onClick={this.handleClick}/>
      </div>Readme file
    );
  }
}
于 2017-07-24T13:26:49.437 回答
4

所以我这样做的方式是: - 而不是重定向 using history.push,我只使用Redirect组件 fromreact-router-dom 当使用这个组件时,你可以通过push=true,它会处理其余的

import * as React from 'react';
import { Redirect } from 'react-router-dom';
class Example extends React.Component {
  componentDidMount() {
    this.setState({
      redirectTo: '/test/path'
    });
  }

  render() {
    const { redirectTo } = this.state;

    return <Redirect to={{pathname: redirectTo}} push={true}/>
  }
}
于 2019-04-01T06:29:40.087 回答
4

我能够通过使用bind(). 我想单击 中的按钮index.jsx,将一些数据发布到服务器,评估响应,然后重定向到success.jsx. 这是我如何解决的...

index.jsx

import React, { Component } from "react"
import { postData } from "../../scripts/request"

class Main extends Component {
    constructor(props) {
        super(props)
        this.handleClick = this.handleClick.bind(this)
        this.postData = postData.bind(this)
    }

    handleClick() {
        const data = {
            "first_name": "Test",
            "last_name": "Guy",
            "email": "test@test.com"
        }

        this.postData("person", data)
    }

    render() {
        return (
            <div className="Main">
                <button onClick={this.handleClick}>Test Post</button>
            </div>
        )
    }
}

export default Main

request.js

import { post } from "./fetch"

export const postData = function(url, data) {
    // post is a fetch() in another script...
    post(url, data)
        .then((result) => {
            if (result.status === "ok") {
                this.props.history.push("/success")
            }
        })
}

success.jsx

import React from "react"

const Success = () => {
    return (
        <div className="Success">
            Hey cool, got it.
        </div>
    )
}

export default Success

所以通过绑定in ,我可以访问thisin ...然后我可以在不同的组件中重用这个函数,只需要确保我记得包含在.postDataindex.jsxthis.props.historyrequest.jsthis.postData = postData.bind(this)constructor()

于 2017-11-21T16:40:57.380 回答
4

这是我的 hack(这是我的根级文件,其中混合了一点 redux - 虽然我没有使用react-router-redux):

const store = configureStore()
const customHistory = createBrowserHistory({
  basename: config.urlBasename || ''
})

ReactDOM.render(
  <Provider store={store}>
    <Router history={customHistory}>
      <Route component={({history}) => {
        window.appHistory = history
        return (
          <App />
        )
      }}/>
    </Router>
  </Provider>,
  document.getElementById('root')
)

然后我可以window.appHistory.push()在我想要的任何地方使用(例如,在我的 redux 存储函数/thunks/sagas 等)我希望我可以使用window.customHistory.push()但由于某种原因react-router似乎从未更新,即使 url 改变了。但是这样我就有了 EXACT 实例的react-router用途。我不喜欢将东西放在全球范围内,这是我会做的少数事情之一。但它比我见过的任何其他选择都要好。

于 2017-08-18T22:54:09.487 回答
3

使用回调。它对我有用!

export function addProduct(props, callback) {
  return dispatch =>
    axios.post(`${ROOT_URL}/cart`, props, config)
    .then(response => {
    dispatch({ type: types.AUTH_USER });
    localStorage.setItem('token', response.data.token);
    callback();
  });
}

在组件中,您只需添加回调

this.props.addProduct(props, () => this.props.history.push('/cart'))
于 2018-03-11T19:53:16.637 回答
2

React 路由器 V4 现在允许使用 history 属性,如下所示:

this.props.history.push("/dummy",value)

然后,只要 location 属性作为 state:{value}非组件状态可用,就可以访问该值。

于 2018-11-30T19:24:46.660 回答
2

由于我们已经在 react 路由器 5 中包含了历史记录,因此我们可以通过参考访问相同的历史记录

import React from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';

function App() {
   const routerRef = React.useRef();
   const onProductNav = () => {
       const history = routerRef.current.history;
       history.push("product");
   }
return (
    <BrowserRouter ref={routerRef}>
        <Switch>
            <Route path="/product">
                <ProductComponent />
            </Route>
            <Route path="/">
                <HomeComponent />
            </Route>
        </Switch>
    </BrowserRouter>
)
}
于 2021-08-08T07:03:35.670 回答
1

step one wrap your app in Router

import { BrowserRouter as Router } from "react-router-dom";
ReactDOM.render(<Router><App /></Router>, document.getElementById('root'));

Now my entire App will have access to BrowserRouter. Step two I import Route and then pass down those props. Probably in one of your main files.

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

//lots of code here

//somewhere in my render function

    <Route
      exact
      path="/" //put what your file path is here
      render={props => (
      <div>
        <NameOfComponent
          {...props} //this will pass down your match, history, location objects
        />
      </div>
      )}
    />

Now if I run console.log(this.props) in my component js file that I should get something that looks like this

{match: {…}, location: {…}, history: {…}, //other stuff }

Step 2 I can access the history object to change my location

//lots of code here relating to my whatever request I just ran delete, put so on

this.props.history.push("/") // then put in whatever url you want to go to

Also I'm just a coding bootcamp student, so I'm no expert, but I know you can also you use

window.location = "/" //wherever you want to go

Correct me if I'm wrong, but when I tested that out it reloaded the entire page which I thought defeated the entire point of using React.

于 2018-09-21T05:49:08.013 回答
0
/*Step 1*/
myFunction(){  this.props.history.push("/home"); }
/**/
 <button onClick={()=>this.myFunction()} className={'btn btn-primary'}>Go 
 Home</button>
于 2018-03-10T08:11:07.420 回答
0

如果您想在将函数作为值传递给组件的道具时使用历史记录,使用react-router 4history您可以简单地在组件的渲染属性中解构道具<Route/>,然后使用history.push()

    <Route path='/create' render={({history}) => (
      <YourComponent
        YourProp={() => {
          this.YourClassMethod()
          history.push('/')
        }}>
      </YourComponent>
    )} />

注意:为了让它工作,你应该将 React Router 的 BrowserRouter 组件包裹在你的根组件周围(例如,它可能在 index.js 中)

于 2020-05-18T18:53:48.883 回答
0

你可以像我这样使用它来登录和许多不同的事情

class Login extends Component {
  constructor(props){
    super(props);
    this.login=this.login.bind(this)
  }


  login(){
this.props.history.push('/dashboard');
  }


render() {

    return (

   <div>
    <button onClick={this.login}>login</login>
    </div>

)
于 2018-03-01T09:33:28.893 回答
0

在 v6 中,应重写此应用程序以使用导航 API。大多数情况下,这意味着将 useHistory 更改为 useNavigate 并更改 history.push 或 history.replace 调用站点。

// This is a React Router v6 app
import { useNavigate } from "react-router-dom";

function App() {
  let navigate = useNavigate();
  function handleClick() {
    navigate("/home");
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );
}

了解更多

于 2021-11-08T13:24:45.517 回答
0

Router用自己的方式创建一个自定义browserHistory

import React from 'react';
import { Router } from 'react-router-dom';
import { createBrowserHistory } from 'history';

export const history = createBrowserHistory();

const ExtBrowserRouter = ({children}) => (
  <Router history={history} >
  { children }
  </Router>
);

export default ExtBrowserRouter

接下来,在您定义 的 Root 上Router,使用以下命令:

import React from 'react';       
import { /*BrowserRouter,*/ Route, Switch, Redirect } from 'react-router-dom';

//Use 'ExtBrowserRouter' instead of 'BrowserRouter'
import ExtBrowserRouter from './ExtBrowserRouter'; 
...

export default class Root extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <ExtBrowserRouter>
          <Switch>
            ...
            <Route path="/login" component={Login}  />
            ...
          </Switch>
        </ExtBrowserRouter>
      </Provider>
    )
  }
}

最后,在需要的地方导入history并使用:

import { history } from '../routers/ExtBrowserRouter';
...

export function logout(){
  clearTokens();      
  history.push('/login'); //WORKS AS EXPECTED!
  return Promise.reject('Refresh token has expired');
}
于 2019-07-05T00:58:52.280 回答