我正在创建一个 React Native 应用程序并使用 redux 和 redux-thunk 来实现我的 API 请求。我想知道如何等待我的操作被分派(dispatch)并确保我的状态已在异步 thunk 逻辑中更新。如果我理解正确,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')
}
最佳答案
在 Redux 中, 当一个 Action 被发送到 store 时,它会使用新的 props 自动更新 UI 的状态。
您可以在 reducer signUpSuccess
中添加一个标志,类似于 isLoggingIn
标志,而不是观察调度的 Action ,并监听 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);
关于javascript - Redux thunk : wait for async function to dispatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56015417/