我对如何将我的 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;
答案 0 :(得分: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,
});
},
},
});
store.subscribe(()=>{
localStorage.setItem('reduxState', JSON.stringify(store.getState()))
})
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')
)