我正在尝试使用redux-persist存储ES6地图,这样我的数据就不会在页面刷新时丢失。这是我尝试使用的代码
const initialState = {
subevents: new Map()
};
const subEventsReducer = (state = initialState, action) => {
switch (action.type) {
case ACTIONS.SET_SUBEVENT: {
const subevents = state.subevents;
subevents.set(action.subevent.key, action.subevent);
return {
...state,
subevents
}
}
default:
return state;
}
};
const transformSubeventMap = createTransform(
(state) => {
return { ...state, subevents: JSON.stringify([...state]) }
},
(state) => {
console.log(state);
return { ...state, subevents: JSON.parse(new Map(state.subevents)) }
}
);
const subevents = persistReducer(
{
version: 1,
key: 'subevents',
storage,
transforms: [transformSubeventMap],
whitelist: ['subevents']
},
subEventsReducer
);
export default subevents;
我想将subevents属性存储为(Date,Array)的Map。知道为什么这不起作用吗?
答案 0 :(得分:0)
我还没有尝试过您的代码,但是我觉得您的转换器有错误。您可能错过了添加.ion-card-header {
display: flex;
justify-content: space-between;
align-items: center;
}
属性:
subevents
但这可能还不够。由于const transformSubeventMap = createTransform(
(state) => {
return { ...state, subevents: JSON.stringify([...state.subevents]) }
},
(state) => {
console.log(state);
return { ...state, subevents: JSON.parse(new Map(state.subevents)) }
}
);
无法处理ES6地图,因此必须将它们转换为数组以正确保存它们。另外,您无需转换为JSON。
尝试这样的事情:
redux-persist
您还可以将带有白名单的选项对象传递给转换器,使其更加简单:
const transformSubeventMap = createTransform(
(state) => {
return { ...state, subevents: Array.from(state.subevents) }
},
(state) => {
console.log(state);
return { ...state, subevents: new Map(state.subevents) }
}
);