我有一个超级简单的问题为什么我的redux状态不能立即更新?
const { reducer, actions } = createSlice({
name: "professionals",
initialState: {
loading: false,
lastFetchList: undefined,
list: undefined,
professional: undefined,
filters: {
virtual: false
}
},
reducers: {
professionalsListRequested: (professionals, action) => {
if (action.payload.withLoading) professionals.loading = true;
},
professionalsListRequestFailed: (professionals, action) => {
professionals.loading = false;
},
professionalsListReceived: (professionals, action) => {
professionals.lastFetchList = Date.now();
professionals.list = action.payload.data.dataArr;
professionals.loading = false;
},
virtualUpdated: (categories, action) => {
categories.filters.virtual = action.payload;
}
},
});
export const { virtualUpdated } = actions;
export default reducer;
这是我的那份。下面是该组件的代码:
const dispatch = useDispatch();
const filters = useSelector((state) => state.professionals.filters);
const handlePressOnVirtual = async () => {
console.log("Before" , filters.virtual)
await dispatch(virtualUpdated(!filters.virtual));
console.log("after" , filters.virtual)
};
当调用handlePressOnVirtual
函数时,console.log(s)打印状态的前一个值。
当你仍然在handlePressOnVirtual
函数中,你仍然在闭包中,所以所有的引用仍然是你现有的filters
因此,您需要等待useSelector
再次调用的另一次重新渲染,然后新值将出现。
- 查看最新更改的一种方法是将日志放入
useEffect
:
useEffect(() => {
console.log("after" , filters.virtual)
},[filters.virtual]);