In the current version of React Router
(v3) I can accept a server response and use browserHistory.push
to go to the appropriate response page. However, this isn't available in v4, and I'm not
sure what the appropriate way to handle this
is.
In this example, using Redux,
components/app-product-form.js calls
this.props.addProduct(props)
when a user submits the form. When
the server returns a success, the user is taken to the Cart
page.
//
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
});
}
How
can I make a redirect to the Cart page from function for React Router
v4?
class="normal">Answer
You can
use the history
methods outside of your components. Try by the
following way.
First, create a
history
object used href="https://www.npmjs.com/package/history" rel="noreferrer">the history
package:
// src/history.js
import {
createBrowserHistory } from 'history';
export default
createBrowserHistory();
Then
wrap it in
(please
note, you should use import { Router }
instead
of import { BrowserRouter as Router
):
}
// src/index.jsx
//
...
import { Router, Route, Link } from 'react-router-dom';
import
history from './history';
ReactDOM.render(
- to="/">Home
- to="/login">Login
exact path="/" component={HomePage} />
component={LoginPage} />
,
document.getElementById('root'),
);
Change
your current location from any place, for
example:
//
src/actions/userActionCreators.js
//
...
import history from '../history';
export function
login(credentials) {
return function (dispatch) {
return
loginRemotely(credentials)
.then((response) => {
//
...
history.push('/');
});
};
}
/>
UPD: You can also see a slightly
different example in href="https://github.com/ReactTraining/react-router/blob/master/FAQ.md#how-do-i-access-the-history-object-outside-of-components"
rel="noreferrer">React Router FAQ.
No comments:
Post a Comment