React Redux Toolkit:如何使用 createSlice 将我的 initialState 存储到 localStorage?

时间:2021-04-25 01:08:41

标签: reactjs redux-toolkit

我对如何将我的 taskSlice 的初始状态存储到我的 localStorage 中有点太困惑了。你能帮我解决这个问题吗?我想要的结果是,如果应用程序运行,initialState 将存储在 localStorage 中。因为我正在做的是在我的组件中使用 useSelector,然后使用 useEffect 来了解是否存在现有的 localStorage 值。如果为 false,则将状态存储在 localStorage 中。

taskSlice.js

import { createSlice } from '@reduxjs/toolkit';
import { v4 as uuidv4 } from 'uuid';

const initialState = [
  {
    _id: uuidv4(),
    title: 'Learn React',
    desc: 'Nec ullamcorper sit amet risus nullam eget felis.',
    isProgress: false,
    isComplete: false,
    priority: 'Minor',
    created: 'johndoe',
    assigned: 'Doe John',
    dateCreated: new Date(),
    dateDue: new Date(),
  },
];

export const taskSlice = createSlice({
  name: 'tasks',
  initialState: initialState,
  reducers: {
addTodo: (state, action) => {
      state.push({
        _id: uuidv4(),
        title: action.payload.taskInfo.title,
        desc: action.payload.taskInfo.description,
        isProgress: false,
        isComplete: false,
        priority: action.payload.taskInfo.priority,
        dateCreated: new Date(),
        created: action.payload.taskInfo.created,
        assigned: action.payload.taskInfo.assigned,
        dateDue: action.payload.taskInfo.dateDue,
      });
    },
  },
});

export const { addTodo } = taskSlice.actions;

export const taskSelector = (state) => state.tasks;

export default taskSlice.reducer;

1 个答案:

答案 0 :(得分:1)

  1. 首先添加一个水合物动作
export const taskSlice = createSlice({
  name: 'tasks',
  initialState: initialState,
  reducers: {
hydrate:(state, action) => {
// do not do state = action.payload it will not update the store
return action.payload
},
addTodo: (state, action) => {
      state.push({
        _id: uuidv4(),
        title: action.payload.taskInfo.title,
        desc: action.payload.taskInfo.description,
        isProgress: false,
        isComplete: false,
        priority: action.payload.taskInfo.priority,
        dateCreated: new Date(),
        created: action.payload.taskInfo.created,
        assigned: action.payload.taskInfo.assigned,
        dateDue: action.payload.taskInfo.dateDue,
      });
    },
  },
});
  1. 在商店刷新时保存状态
store.subscribe(()=>{
  localStorage.setItem('reduxState', JSON.stringify(store.getState()))
})
  1. 在将 store 交给提供程序之前,如果有待办事项,请在 localstorage 中查找,使用有效载荷分派 hydrate 操作。这样做是明智的,而不是在功能组件中使用它,因为它很容易推理。
const getTodosFromLocalStorage = () => {
  try { 
    const persistedState = localStorage.getItem('reduxState') 
    if (persistedState) 
      return JSON.parse(persistedState)
  }
  catch (e){ 
    console.log(e)
  }
}

const todos = getTodosFromLocalStorage()
if(todos){
  store.dispatch(hydrate(todos))
}
// All safe give it to Provider
ReactDOM.render(
  <React.StrictMode>
        <Provider store={store}>
            <App />
        </Provider>    
  </React.StrictMode>,
  document.getElementById('root')
)