reactjs - 如何更新 React 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()
解决方案
Redux 是内存存储。然后你刷新页面它会消失。
所以你必须使用 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;
推荐阅读
- objective-c - 如何使用 CVPixelBufferCreate 创建黑色的 CMSampleBufferRef?
- php - Laravel 使用 vagrant:php artisan migrate --seed 给出错误
- python - WxPython 退出按钮并不总是有效
- java - 假阳性和假阴性
- google-container-registry - 从 gcr.io 拉取时权限失败
- python - 捕获 UnboundLocalError 异常
- react-native - 在android react native上更改导航栏颜色(仅在单个页面上,而不是通过应用程序)
- python - 数据框列中两个值的平均值
- javascript - 将元数据添加到 HTML5 音频流
- reactjs - 三元表达式不更新 jsx 模板