我最近用我的Next.js项目设置了redux,现在我正在处理持久化redux数据,这样在每次页面刷新时,我都可以拥有持久化状态。所以我添加了redux-persist来处理这种情况,因为它是使用react-redux的最佳解决方案,但我不知道为什么它不能在使用next-redux-wrapper或withRedux库的next.js中工作。所以请帮助我解决这个问题,有没有像redux-persist这样的东西存在?(我不想要cookie的解决方案),如果有,那么请给我一些例子的参考资料,这将是非常有帮助的。先谢谢你...
实际上,我试图在每次页面刷新后保持redux状态,所以我也使用了redux-persist和next-redux-wrapper,但我收到了错误
/store.js
import { createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunkMiddleware from 'redux-thunk'
import { persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
const persistConfig = {
timeout: 0,
key: 'root',
storage,
};
const persistedReducer = persistReducer(persistConfig, reducer);
export default () => {
return createStore(persistedReducer,
composeWithDevTools(
applyMiddleware(
thunkMiddleware
)
));
};/_app.js
import App, { Container } from 'next/app'
import React from 'react'
import { Provider } from 'react-redux'
import withRedux from 'next-redux-wrapper';
import { PersistGate } from 'redux-persist/integration/react';
import { persistStore } from 'redux-persist';
import store from '../store';
class MyApp extends App {
static async getInitialProps ({Component, ctx}) {
return {
pageProps: (Component.getInitialProps ? await Component.getInitialProps(ctx) : {})
};
}
render () {
const { Component, pageProps, reduxStore } = this.props;
const persistor = persistStore(store);
return (
<Container>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<Component {...pageProps} />
</PersistGate>
</Provider>
</Container>
)
}
}我希望它会保持状态,但我得到的错误如下:"redux-persist无法创建同步存储。回落到内存storage.TypeError: baseReducer不是一个函数“
发布于 2020-08-15 03:01:48
创建您自己的storage.js文件。将文件放在主项目文件夹中。使用下面的代码。
import createWebStorage from "redux-persist/lib/storage/createWebStorage";
const createNoopStorage = () => {
return {
getItem(_key) {
return Promise.resolve(null);
},
setItem(_key, value) {
return Promise.resolve(value);
},
removeItem(_key) {
return Promise.resolve();
},
};
};
const storage = typeof window !== "undefined" ? createWebStorage("local") : createNoopStorage();
export default storage;转到在Nextjs示例中创建的store.js文件。将import storage from 'redux-persist/lib/storage'替换为import storage from './storage',以导入您创建的文件。
发布于 2020-08-15 05:50:47
我在这里看不到你的减水器,但我猜你不是在处理再水化的案子。为了在页面刷新上保持状态,你的reducer应该处理再水化的情况。这是我的代码中的一个示例:
const Account = (state= INIT_STATE, action) => {
switch (action.type) {
/// other cases here....
case REHYDRATE:
const rehydrated = (action && action.payload && action.payload.Account) || {}
return { ...state, ...rehydrated }
default: return { ...state };https://stackoverflow.com/questions/54036503
复制相似问题