【问题标题】:How to push route in history using redux-saga如何使用 redux-saga 推送历史路线
【发布时间】:2023-09-16 19:43:01
【问题描述】:

我正在使用 react、redux、saga 和 router v4。

我想在我的传奇中进行重定向,但我不知道如何访问 history 对象,因为我正在使用 BrowserRouter

我想要做的类似于:

export function * callWS (action) {
   const result = yield call(data, ws)

   if (result.status === 201) {
          yield call(history.push, '/success')
   }
}

但是,由于我使用的是BrowserRouter,所以我从未创建过这个history 对象。 关于如何做到这一点的任何想法?

【问题讨论】:

  • 如果你在你的应用中使用react-router-redux,你可以从这个包中导入putreplace动作。

标签: reactjs react-router-v4 redux-saga html5-history


【解决方案1】:

我遇到了类似的问题,我想出了这个解决方案..

在您的 app.js 中创建历史记录并将其导出:

import createHistory from 'history/createBrowserHistory';
const history = createHistory();
// ...
export { history };

然后在您的 sagas 中,您可以创建一个处理导航的 forwardTo 函数:

import { call, fork, takeLatest, cancel, take } from 'redux-saga/effects';
import { history } from 'app';

function* myFunction() {
  try {
    // do something
    yield call(forwardTo, '/');
  } catch(e){
    // Do something
  }
}

export default function* defaultSaga() {
  const submitWatcher = yield fork(takeLatest, SOMETHING, submitForm);
   yield take(LOCATION_CHANGE);
   yield cancel(submitWatcher);
 }

function forwardTo(location) {
 history.push(location);
}

【讨论】: