Redux在内存存储中。然后刷新页面,它就会消失。
我得到了用户的预定义数据,该用户在代码顶部使用useSelectore状态登录,但当我想更改用户配置文件的值时
onSubmit=
{async values => {
await updateUser(values).then((data) => {
store.dispatch(setCurrentUser(data));
store.subscribe();
console.log("store", store.getState().auth.user);//it shows the state has been updated
});
}}
它在视图中发生了更改,并在数据库中进行了更新,但当我刷新页面时,它显示的是存储中相同的旧值我的减速器
const auth = createSlice({
name: 'auth',
initialState,
reducers: {
setCurrentUser : (state, action) => {
state.isAuthenticated = true;
state.user = action.payload;
}....})
更新状态的文档更让我困惑
function select(state) {
return state.some.deep.property
}
let currentValue
function handleChange() {
let previousValue = currentValue
currentValue = select(store.getState())
if (previousValue !== currentValue) {
console.log(
'Some deep nested property changed from',
previousValue,
'to',
currentValue
)
}
}
const unsubscribe = store.subscribe(handleChange)
unsubscribe()
因此,您必须使用localStorage或indexedDB来存储数据。
看看这样的图书馆以更好地理解https://github.com/rt2zz/redux-persist
您需要从localStorage获取初始状态,并在每次更改时将您的redux状态保持到localStorage。
const storeKey = 'your-unique-key-name';
function persist() {
localStorage[storeKey] = JSON.stringify(store.getState);
}
store.subscribe(persist);
...
const initialState = localStorage[storeKey] ? JSON.parse(localStorage[storeKey]) : undefined;