【发布时间】:2022-11-12 07:55:26
【问题描述】:
大家好,对不起,我的英语是我的第二语言. 所以我有一个看起来像这样的 Redux 状态:
const initialState = {
user: null,
isLoading: false,
};
每次我加载主屏幕(我使用的是 React Native)时,我都会从本地存储中获取一个用户并将其置于以下状态:
useEffect(() => {
dispatch(getMe());
dispatch(getCategories());
}, []);
使用 getMe 函数,我从本地存储中获取用户,使用 getCategories 函数,我向 api 发出请求并获取数据。但是如果我在获取类别时采用状态值,我会得到一个空值(默认值):
// Get categories
export const getCategories = createAsyncThunk(
"categories/get",
async (_, thunkAPI) => {
try {
console.log(thunkAPI.getState().user.user);
// The thunkAPI.getState().user.user value is null
return await categoryService.getCategories();
} catch (error) {
thunkAPI.rejectWithValue(error);
}
}
);
我只是对如果我超时 getCategories 函数会发生什么感兴趣:
useEffect(() => {
dispatch(getMe());
setTimeout(() => dispatch(getCategories()), 1);
}, []);
它有效。但我真的不认为这是一个好方法,那么我该如何“正确”解决这个问题?
先谢谢了!!!
【问题讨论】:
标签: react-native redux redux-toolkit