react how to navigate router in redux-saga?

Viewed 6049

version: "react-router-dom": "^4.1.2", "react-router-redux": "^5.0.0-alpha.8",

i can navigate router successfully in my component by this way:

this.props.history.push('/cart')

then i wanna navigate router in my saga.js , i tried some ways and they all not worked:

const history = createHistory();



yield call(history.push, '/cart')
yield call(put('/cart)//react-router-redux
history.push('/cart')

these ways can change the url , but the page would not render. i add the page component withRouter , and it also not work. can someone help me thanks!

here is my some settings:

const render = Component =>
  ReactDOM.render(
      <Provider store={store}>
        <AppContainer>
          <Component />
        </AppContainer>
      </Provider>
    ,
    document.getElementById('root')
  );

class App extends Component {

  render () {
    return (
      <ConnectedRouter history={history}>
        <div>
          <Header/>
          <Nav/>
          <ScrollToTop>
            <Route render={({location}) => (
              <ReactCSSTransitionGroup
                transitionName="fade"
                transitionEnterTimeout={300}
                transitionLeaveTimeout={300}>
                <div key={location.pathname} className="body">
                  <Route location={location} exact path="/" component={HomePageContainer}/>
                  <the other component>
                  .....
                </div>
              </ReactCSSTransitionGroup>)}/>
          </ScrollToTop>
          <Footer/>
        </div>
      </ConnectedRouter>
    )
  }
}

===============================================================

i fixed this problem by this way: user Router instead of BroswerRouter,and then

 history.push('/somerouter')
4 Answers

You can use push method from react-router-redux. For example:

import { push } from "react-router-redux";

yield put(push('/')); /* inside saga generator function*/

You can use browserHistory of react-router.

import { browserHistory } from "react-router";

yield browserHistory.push("/"); //put the path of the page you want to navigate to instead of "/"

I've found a simple solution. Dispatch the push function that is inside the component to the saga.

class App extends Component {
    foo = () => {
        const { dispatch } = this.props;

        dispatch({
            type: 'ADD_USER_REQUEST',
            push: this.props.history.push <<-- HERE
        });
    }

    render() { ... }
}

Inside the saga, just use the push like this:

function* addUser(action) {
    try {
        yield put(action.push('/users'));

    } catch (e) {
        // code here...
    }
}

Had to resolve similar issue recently. react-router-redux project is deprecated now, so I used connected-react-router - works well.

Related