应用于存储后修改 Redux Persist 设置?
Modify Redux Persist settings after applied to store?
redux-persist应用到store后有什么方法可以修改设置?或者这只能在应用程序的 bootstrap 处定义?
除了用新配置重新创建商店,我想不出别的办法。您可以创建一个上下文来提供一个功能来更改应用程序内任何位置的商店配置。缺点是它会重新加载整个应用程序。
configureStore
export default (config, initialState) => {
const persistConfig = {
key: "root",
storage,
...config
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
let store = createStore(persistedReducer, initialState);
let persistor = persistStore(store);
return { store, persistor };
};
应用程序
...
import { StoreContext } from "./StoreContext";
import { initialState } from "./rootReducer";
import configureStore from "./configureStore";
const initialStoreConfig = configureStore({}, initialState);
function App() {
const [storeConfig, setStoreConfig] = useState(initialStoreConfig);
const changeStoreConfig = React.useCallback(
(config) => {
setStoreConfig(configureStore(config, storeConfig.store.getState()));
},
[storeConfig.store]
);
return (
<StoreContext.Provider value={{ changeStoreConfig }}>
<Provider store={storeConfig.store}>
<PersistGate
loading={<div>loading</div>}
persistor={storeConfig.persistor}
>
<div className="App">
<h1>Hello World</h1>
<p>A simple toggle:</p>
<Toggle />
</div>
</PersistGate>
</Provider>
</StoreContext.Provider>
);
}
redux-persist应用到store后有什么方法可以修改设置?或者这只能在应用程序的 bootstrap 处定义?
除了用新配置重新创建商店,我想不出别的办法。您可以创建一个上下文来提供一个功能来更改应用程序内任何位置的商店配置。缺点是它会重新加载整个应用程序。
configureStore
export default (config, initialState) => {
const persistConfig = {
key: "root",
storage,
...config
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
let store = createStore(persistedReducer, initialState);
let persistor = persistStore(store);
return { store, persistor };
};
应用程序
...
import { StoreContext } from "./StoreContext";
import { initialState } from "./rootReducer";
import configureStore from "./configureStore";
const initialStoreConfig = configureStore({}, initialState);
function App() {
const [storeConfig, setStoreConfig] = useState(initialStoreConfig);
const changeStoreConfig = React.useCallback(
(config) => {
setStoreConfig(configureStore(config, storeConfig.store.getState()));
},
[storeConfig.store]
);
return (
<StoreContext.Provider value={{ changeStoreConfig }}>
<Provider store={storeConfig.store}>
<PersistGate
loading={<div>loading</div>}
persistor={storeConfig.persistor}
>
<div className="App">
<h1>Hello World</h1>
<p>A simple toggle:</p>
<Toggle />
</div>
</PersistGate>
</Provider>
</StoreContext.Provider>
);
}