将Redux-Persist与REST API结合使用



我已经学习了无数关于redux-persistent的教程,相信我在redux-toolkit应用程序中实现了它。然而,我认为我这方面的基本理解存在脱节。我可以在使用REST API的应用程序上使用persistent吗?还是需要在后端服务器上设置它才能工作?如果你不能为一个使用REST API的应用程序使用持久化,我该如何在一个使用Redux-Toolkit的应用程序上使状态持久化?在我浏览器的开发工具中的应用程序中,它显示我的状态已经保存,但当我关闭浏览器窗口并重新打开时,我发现我的购物车是空的。这是我的代码,以防我遗漏了什么:

存储js

import cartReducer from "./features/Cart/cartSlice"
import modalReducer from "./features/Modal/modalSlice"
//Persist
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";

const persistConfig = {
key: "persist-key",
storage
}
const persistedReducer = persistReducer(persistConfig, cartReducer)
const store = configureStore({
reducer: {
persistedReducer: persistedReducer,
cart: cartReducer,
modal: modalReducer,
},
middleware: (getDefaultMiddleware) => getDefaultMiddleware({
serializableCheck: false
})
})
const persistor = persistStore(store)
export default store;
export { persistor }

索引js

import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

import store, {persistor} from "./store"
import { PersistGate } from 'redux-persist/integration/react';
import { Provider } from 'react-redux';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<PersistGate persistor={persistor}>
<App />
</PersistGate>
</Provider>
</React.StrictMode>
);

任何帮助都将不胜感激。

是的,您可以使用redux-persistent将数据保存在客户端,但请记住,永远不应该保留合理的数据。并且使用它只保留必要的数据,如会话数据设置等。

您可以从react redux库中检索所有正常的redux数据,处理程序useSelector将返回您的当前状态。

所以您的后端并没有实现任何东西来保证您的redux流,这是前端的全部责任。

最新更新