本文介绍了如何在 Redux 应用程序的 localstorage 中存储我的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 React 和 Redux 构建一个 Trello 克隆.
I am trying to build a Trello clone using React and Redux.
申请详情:
- 该应用程序包含 4 列,分别称为 TODO、DOING、DONE 和 REJECTED
- 我可以将卡片添加到 4 列中的任何一列.
- 卡片中只有纯文本.
- 可以使用名为 react-beautiful-dnd 的包将卡片进一步移动到任何列中.
- 每张卡片上还有一个删除按钮,用于删除添加的卡片.
我想做什么?
- 我有一个示例数据,该数据在首次加载应用程序时首先呈现.
- 数据只是演示,包含每张卡片的 id 和 text 属性.
- 我想使用 localstorage 添加卡并进一步删除卡.
- 我想可能使用 Redux 订阅来实现这一点.
我在处理 Redux 和 localstorage 方面没有太多经验.我怎样才能做到这一点?任何帮助将不胜感激并且非常需要.
我有我的代码和盒子,我在那里运行我的应用程序.请考虑检查出来帮助我.https://codesandbox.io/s/small-violet-zmbtf
I have my codesandbox where I have my application running. Please consider checking out to help me out.https://codesandbox.io/s/small-violet-zmbtf
推荐答案
你必须使用 redux persist
// configureStore.js
import { createStore } from 'redux'
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web
import rootReducer from './reducers'
const persistConfig = {
key: 'root',
storage,
}
const persistedReducer = persistReducer(persistConfig, rootReducer)
export default () => {
let store = createStore(persistedReducer)
let persistor = persistStore(store)
return { store, persistor }
}
// App.js
import { PersistGate } from 'redux-persist/integration/react'
// ... normal setup, create store and persistor, import components etc.
const App = () => {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<RootComponent />
</PersistGate>
</Provider>
);
};
编辑了以下检查:将代码沙盒更改为:
Edited check below:change codesandbox to:
store/index.js:
store/index.js:
// store/index.js:
import { createStore } from "redux";
import { persistStore } from "redux-persist";
import rootReducer from "../reducers";
export const store = createStore(rootReducer);
export const persistor = persistStore(store);
*******减速器/index.js:
******* reducers/index.js:
// reducers/index.js:
import { combineReducers } from "redux";
import { persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import listReducers from "./listReducers";
const persistConfig = {
key: "root",
storage,
whitelist: ["lists"]
};
export default persistReducer(persistConfig, combineReducers({
lists: listReducers
}));
根项目 index.js:
root project index.js:
// index.js:
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";
import { store, persistor } from "./store";
import "./styles/main.scss";
import App from "./components/App";
import * as serviceWorker from "./serviceWorker";
ReactDOM.render(
<Provider store={store}>
<PersistGate persistor={persistor}>
<App />
</PersistGate>
</Provider>,
document.getElementById("root")
);
serviceWorker.unregister();
这篇关于如何在 Redux 应用程序的 localstorage 中存储我的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!