小编典典

如何在React Router v4中推送到历史记录?

reactjs

在当前版本的React
Router(v3)中,我可以接受服务器响应并用于browserHistory.push转到相应的响应页面。但是,这在v4中不可用,我不确定哪种适当的处理方式。

在此示例中,使用Redux,当用户提交表单时, components / app-product-form.js
调用this.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的功能重定向到购物车页面?


阅读 247

收藏
2020-07-22

共1个答案

小编典典

您可以在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中看到一个稍微不同的示例。

2020-07-22