当我试图将存储添加到我的应用中时,在标头上出现错误
这是我的商店.js代码
import { createStore, applyMiddleware } from 'redux';
import { persistStore } from 'redux-persist';
import logger from 'redux-logger';
import createSagaMiddleware from 'redux-saga';
import { composeWithDevTools } from 'redux-devtools-extension';
import rootReducer from './root-reducer';
import rootSaga from './root-saga';
const sagaMiddleware = createSagaMiddleware();
const middlewares = [sagaMiddleware];
//if (process.env.NODE_ENV === 'development') {
middlewares.push(logger);
//}
sagaMiddleware.run(rootSaga);
const configureStore = () => {
const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(...middlewares)));
const persistor = persistStore(store);
return { persistor, store };
};
export default configureStore;
这是我的index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from "react-router-dom";
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import App from './App';
import configureStore from './redux/store';
ReactDOM.render(
<React.StrictMode>
<Provider store={configureStore}>
<Router>
<PersistGate persistor={configureStore}>
<App />
</PersistGate>
</Router>
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
你能帮我找出这里的问题吗?提前感谢
运行传奇应该在创建这样的存储之后:
...
const configureStore = () => {
const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(...middlewares)));
sagaMiddleware.run(rootSaga);
const persistor = persistStore(store);
return { persistor, store };
};
这里的另一点,关于TypeError: store.getState is not a function
:您返回的是函数,而不是函数的结果:所以通常应该是这样的:
const configureStore = () => {
const store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(...middlewares))
);
const persistor = persistStore(store);
sagaMiddleware.run(rootSaga);
return { persistor, store };
};
export default configureStore();
这里没有返回persistor,但应用程序可以工作。有关于如何添加redux-persist
的说明https://github.com/rt2zz/redux-persist#basic-用法,但您需要单独获得存储和持久存储,如:
import configureStore from "./store";
ReactDOM.render(
<React.StrictMode>
<Provider store={configureStore.store}>
<Router>
<App />
</Router>
</Provider>
</React.StrictMode>,
document.getElementById("root")
);```
获取错误:在运行Saga之前,您必须使用applyMiddleware 在Store上安装Saga中间件
错误解释
你的错误表明你试图过早地执行传奇故事解释您之前要运行中间件。因此,您的解决方案是在创建存储后执行`saggaMiddleware.run((。
根据您的代码发生了什么
在用composeWithDevTools(applyMiddleware(...middlewares))
在第三行安装商店之前,您正试图执行sagaMiddleware.run()
方法
解决方案
这里有一个关于您的行声明顺序的解决方案+在返回执行RunSagaMiddleware之前再添加一行
const runSagaMiddleware = () => sagaMiddleware.run(rootSaga);
const configureStore = () => {
const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(...middlewares)));
const persistor = persistStore(store);
runSagaMiddleware();
return { persistor, store };
};