【问题标题】:" Error: Before running a Saga, you must mount the Saga middleware on the Store using applyMiddleware "“ 错误:在运行 Saga 之前,您必须使用 applyMiddleware 在 Store 上挂载 Saga 中间件”
【发布时间】:2021-01-22 13:20:47
【问题描述】:

How to configure redux saga with redux store,我试过了,但我得到了这个错误,它在顶部“

import React from "react" import { Provider } from "react-redux" 
import { createStore as reduxCreateStore, applyMiddleware } from "redux" 
import createSagaMiddleware from "redux-saga" 
import "regenerator-runtime/runtime" 
import rootReducer from "./reducers" 
import sagas from "./sagas"

const sagaMiddleware = createSagaMiddleware() 
const createStore = () =>  reduxCreateStore(
    rootReducer,
    applyMiddleware(sagaMiddleware),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()   )

sagaMiddleware.run(sagas);

export default ({ element }) => (   <Provider store={createStore()}>{element}</Provider> )

【问题讨论】:

    标签: react-redux redux-saga


    【解决方案1】:

    正如错误所说,您在创建商店之前调用了sagaMiddleware.run。在上面的行中,您创建了一个最终创建 store 的函数(一旦在 react 组件中调用它),但这只有在您尝试运行中间件之后才会发生,这为时已晚。

    根据您的需要,此问题有两种解决方案。

    a) 要么摆脱工厂,立即创建商店。

    const sagaMiddleware = createSagaMiddleware() 
    const store = reduxCreateStore( // notice the missing () =>
        rootReducer,
        applyMiddleware(sagaMiddleware),
        window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()   )
    
    sagaMiddleware.run(sagas);
    
    export default ({ element }) => (   <Provider store={store}>{element}</Provider> )
    

    b) 将中间件逻辑移入 create store 函数中

    const createStore = () => {
        const sagaMiddleware = createSagaMiddleware() 
        reduxCreateStore(
            rootReducer,
            applyMiddleware(sagaMiddleware),
            window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
        )
        sagaMiddleware.run(sagas);
        return store;
    }
    
    export default ({ element }) => (   <Provider store={createStore()}>{element}</Provider> )
    

    我会推荐第一个,除非有特殊原因需要工厂代替。

    【讨论】:

      猜你喜欢
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 2020-06-22
      相关资源
      最近更新 更多