我正在创建一个React本地应用程序,并使用redux和redux-thunk来实现我的API请求。我想知道如何等待我的操作被分派,并确保我的状态已经在异步逻辑中被更新。如果我理解正确的话,await
将等待thunk的结束,但是该操作还没有被分派。虽然,正如您在我的用法中所看到的,我需要修改状态以相应地处理其余的代码。
actions/user.js
export const tryLogin = (
email: string,
password: string,
sessionToken: string = ''
): Function => async (dispatch: Function) => {
const logUser = () => ({ type: LOG_USER })
const logUserSuccess = (data: any, infos: any) => ({
type: LOG_USER_SUCCESS,
data,
infos,
})
const logUserError = (signinErrorMsg: string) => ({
type: LOG_USER_ERROR,
signinErrorMsg,
})
dispatch(logUser())
try {
{ /* Some API requests via axios */ }
dispatch(logUserSuccess(responseJson, infos))
return true
} catch (error) {
{ /* Error handling code */ }
dispatch(logUserError(error.response.data.error))
return false
}
reducers/user.js
case LOG_USER:
return {
...state,
isLoggingIn: true,
}
case LOG_USER_SUCCESS:
return {
...state,
isLoggingIn: false,
data: action.data,
infos: action.infos,
error: false,
signinErrorMsg: '',
}
case LOG_USER_ERROR:
return {
...state,
isLoggingIn: false,
error: true,
signinErrorMsg: action.signinErrorMsg,
}
RegisterScreen.js
if (await trySignup(
emailValue,
firstNameValue,
lastNameValue,
passwordValue,
birthdateValue,
genderValue
)
) {
if (userReducer.data) {
navigation.navigate('Secured')
}
发布于 2019-05-06 20:36:53
在Redux中,当一个Action被分派到商店时,它将用新的道具自动更新UI的状态。
您可以在还原器signUpSuccess
中添加一个类似于isLoggingIn
标志的标志,并侦听componentDidUpdate
生命周期方法中的更改,而不是观看分派的操作。
可以单独调用trySignup
(如事件、formSubmit、按钮单击等)。
RegisterScreen.js
class RegisterScreen extends React.Component{
...
componentDidUpdate(prevProps) {
if (prevProps.signUpSuccess !== this.props.signUpSuccess){
if (this.props.signUpSuccess) {
navigation.navigate('Secured')
}
}
}
...
}
const mapStateToProps = (state) => ({
signUpSuccess: state.userReducer.signUpSuccess,
});
export default connect(mapStateToProps)(RegisterScreen);
发布于 2019-05-06 21:05:23
如果我正确理解,等待将等待结束的雷击,但行动还没有发出。
https://stackoverflow.com/questions/56015417
复制相似问题