React native 使用return语句与使用async dispatch的存储更新来执行操作
我正在处理一个react原生项目,需要一些关于在异步调度中使用return语句与使用异步调度的存储更新来执行操作的意见React native 使用return语句与使用async dispatch的存储更新来执行操作,react-native,redux,react-hooks,redux-thunk,React Native,Redux,React Hooks,Redux Thunk,我正在处理一个react原生项目,需要一些关于在异步调度中使用return语句与使用异步调度的存储更新来执行操作的意见 const initialProfile = { userId: ‘’, name: ‘’, age: null, isFetchingProfile: false, profileFetchError: null, } export const fetchUserProfile = (token) => async (dispa
const initialProfile = {
userId: ‘’,
name: ‘’,
age: null,
isFetchingProfile: false,
profileFetchError: null,
}
export const fetchUserProfile = (token) => async (dispatch) => {
const response = { user: null, error: null }; // For case 2
try {
dispatch(getUserProfileStart())
const response = await fetchProfile(token);
const responseJson = await response.json();
if (responseJson.ok) {
dispatch(getUserProfileSuccess(responseJson));
response.user = responseJson; // For case 2
} else {
dispatch(getUserProfileFailure(‘Non ok response’));
response.error = ’Non ok response’; // For case 2
}
} catch (error) {
dispatch(getUserProfileFailure(error.message));
response.error = error.message; // For case 2
}
return response; // For case 2
}
案例1:使用商店更新执行某些操作
useEffect(() => {
if (token) {
dispatch(fetchUserProfile())
}
}, [token])
useEffect(() => {
if (userId) {
// Do something here
}
}, [userId]) // userId from a selector
useEffect(() => {
if (profileFetchError) {
// Do something here
}
}, [profileFetchError]) // profileFetchError from a selector
案例2:使用return语句,然后等待执行操作
const getUserProfile = async () => {
const { user, error } = await dispatch(fetchUserProfile());
if (user) {
// Handle user
} else {
// Handle error
}
}
useEffect(() => {
if (token) {
getUserProfile();
}
}, [token])
有人能给我解释一下为什么有人更喜欢一个而不是另一个吗?为什么不将这三个动作组合在一起并发送给我呢。该操作可以调用其他3个操作:
firstAction(dispatch,getState)(参数)。然后(result=>secondAction(dispatch,getState)(result.user))