【问题标题】:react how to navigate router in redux-saga?反应如何在 redux-saga 中导航路由器?
【发布时间】:2018-04-15 15:48:42
【问题描述】:

版本:“react-router-dom”:“^4.1.2”, "react-router-redux": "^5.0.0-alpha.8",

我可以通过这种方式在我的组件中成功导航路由器:

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

然后我想在我的 saga.js 中导航路由器,我尝试了一些方法,但它们都不起作用:

const history = createHistory();



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

这些方法可以改变 url ,但页面不会呈现。 我用Router添加了页面组件,它也不起作用。 谁能帮帮我谢谢!

这是我的一些设置:

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>
    )
  }
}

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

我通过这种方式解决了这个问题:用户路由器而不是 BroswerRouter,然后

 history.push('/somerouter')

【问题讨论】:

标签: reactjs react-router jsx redux-saga react-router-redux


【解决方案1】:

您可以使用react-router-redux 中的push 方法。例如:

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

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

【讨论】:

  • 页面仍未呈现
【解决方案2】:

我找到了一个简单的解决方案。 将组件内部的 push 函数分派到 saga。

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

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

    render() { ... }
}

在 saga 中,只需像这样使用 push:

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

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

【讨论】:

    【解决方案3】:

    您可以使用browserHistoryreact-router

    import { browserHistory } from "react-router";
    
    yield browserHistory.push("/"); //put the path of the page you want to navigate to instead of "/"
    

    【讨论】:

      猜你喜欢
      • 2019-12-30
      • 2018-09-04
      • 2021-03-29
      • 2016-04-10
      • 2016-10-10
      • 1970-01-01
      • 2017-11-02
      • 2020-10-27
      • 2020-12-24
      相关资源
      最近更新 更多