如何在 Next.js 应用程序中使用 redux-saga 进行路由

时间:2021-03-26 00:20:49

标签: redux routes next.js redux-saga connected-react-router

我正在尝试将我的 React 应用迁移到 next.js 应用。

  1. 我喜欢 redux-saga
  2. 我喜欢 redux-saga 逻辑中的路由
  3. 我想像以前一样在 redux-saga 逻辑中进行路由!

但我不知道如何做到这一点。 问题是..

  1. 如何在 Next.js 中使用 redux-saga 逻辑进行路由?
  2. 这样做是不好的做法吗?我认为将路由逻辑放在 saga 上似乎更合理。但我认为这不是一种流行的方式。为什么很多人不使用它?

帮助了解我的情况。 我通常在 React 应用程序中做路由,如下所示

以我的一个传奇逻辑为例

export function* deletePost(action) {
  const { postId } = action;
//delete post 
  yield api.postApi.deletePost(postId);
//route page to home ("/")
  yield put(actions.router.push("/"));
}

我使用“connected-react-router”来做到这一点。 和 actions.router 从下面的文件中导出。

import { routerActions as router } from "connected-react-router"
export { router }

下面是我如何配置我的 redux store

import { applyMiddleware, compose, createStore } from "redux";
import createSagaMiddleware from "redux-saga";
import { routerMiddleware } from "connected-react-router";
import { createBrowserHistory } from "history";
import { composeWithDevTools } from "redux-devtools-extension";

import { createRootReducer } from "data/rootReducer";
import rootSaga from "data/rootSaga";

const history = createBrowserHistory();
const sagaMiddleware = createSagaMiddleware();
const rootReducer = createRootReducer(history);

const env = process.env.NODE_ENV;
let composeFn = composeWithDevTools;
if (env === "production") {
  composeFn = compose;
}
export default function configureStore() {
  const store = createStore(
    rootReducer,
    composeFn(applyMiddleware( sagaMiddleware, routerMiddleware(history)))
  );

  sagaMiddleware.run(rootSaga);

  return { history, store };
}

0 个答案:

没有答案