我想实现Redux"订阅"正如Dan Abramov在本视频中解释的那样,将某些状态更改自动保存到localstorage的方法: Persisting the State to the Local Storage
我在视频中做了同样的事情,但我得到了错误:
TypeError: __webpack_require__.i(...) is not a function
项目没有加载。该错误指向store.js文件中的store.subscribe
函数。你能看到这里的错误吗?有什么错误的顺序或什么?
这是store.js文件(其他导入除外):
import {throttle} from 'lodash/throttle';
const sagaMiddleware = createSagaMiddleware();
const logger = createLogger({
collapsed: true,
});
const middlewares = [
sagaMiddleware,
routerMiddleware(history),
];
const enhancers = [
applyMiddleware(...middlewares)
];
const composeEnhancers =
process.env.NODE_ENV !== 'production' &&
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : compose;
const persistedState = loadState();
const store = createStore(
reducers,
persistedState,
composeEnhancers(...enhancers)
);
store.subscribe(throttle(() => {
saveState({
cart: store.getState().cart
});
}), 1000);
sagaMiddleware.run(rootSaga);
export default store;
如果我评论" store.subscribe"阻止,错误消失
// store.subscribe(throttle(() => {
// saveState({
// cart: store.getState().cart
// });
// }), 1000);
Store.js
导入" index.js
"并提交提供者:
<Provider store={store}>
&#34; reducers
&#34; (在createStore方法中)是一个文件,其中所有的reducer被组合在一起(使用combineReducers)。
&#34; localStorageHanding
&#34;文件我命名与Abramovs示例不同,与导入&#34; localStorage&#34;的文件存在一些冲突。 ,我不认为localStorage需要导入,但这不是问题..)。
localStorageHandling的saveState和loadState函数与视频完全相同:
export const loadState = () => {
try{
const serializedState = localStorage.getItem('state');
if(serializedState === null){
return undefined;
}
return JSON.parse(serializedState);
}catch(err){
return undefined;
}
}
export const saveState = (state) => {
try{
const serializedState = JSON.stringify(state);
localStorage.setItem('state', serializedState);
}catch(err){
}
}
我有
"react-redux": "^5.0.3",
"react": "^15.5.0",
答案 0 :(得分:0)
应该从主入口点导入throttle
作为命名导入,还是从lodash/throttle
import { throttle } from 'lodash';
// or
import throttle from 'lodash/throttle';