Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

reactjs - Use history.push in action creator with react-router-v4?

The only working method that I found to work this out without using react-router-redux to route from action creator async action completion is by passing the history prop from the component to action creator and doing:

history.push('routename');

Since BrowserRouter ignores the history prop passed to it thus we cannot use custom history objects with browserhistory.

What is the best possible way to work this out?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of using BrowserRouter you could use the Router with custom history like

import { Router } from 'react-router'

import createBrowserHistory from 'history/createBrowserHistory'

export const history = createBrowserHistory()

<Router history={history}>
  <App/>
</Router>

in which case your history.push() will work. With BrowserRouter history.push doesn't work because Creating a new browserHistory won't work because <BrowserRouter> creates its own history instance, and listens for changes on that. So a different instance will change the url but not update the <BrowserRouter>.

Once you create a custom history, you can export it and then import it in your action creator and use it to navigate dynamically like

import { history } from '/path/to/index';

const someAction = () => {
    return dispatch => {
        ApiCall().then((res) => {
            dispatch({type: 'SOME_CALL', payload: res })
            history.push('/home');
        })
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...