在 react redux 的动作创建者中返回带有承诺的调度

Kno*_*ker 2 javascript reactjs redux react-redux redux-actions

我有一个actionCreators/actions/authenticate.js到单独的逻辑行动派出由终极版组件反应

这是我的authenticate.js,这是我的actionCreators

export function login(email, password) { // Fake authentication function
    return async dispatch => {
        dispatch(loginRequest()); // dispatch a login request to update the state
        try {
            if (email.trim() === "test123@nomail.com" && password === "123456") { //If the email and password matches
                const session = { token: "abc1234", email: email, username: "test123" } // Create a fake token for authentication
                await AsyncStorage.setItem(DATA_SESSION, JSON.stringify(session)) // Stringinfy the session data and store it
                setTimeout(() => { // Add a delay for faking a asynchronous request
                    dispatch(loginSuccess(session)) // Dispatch a successful sign in after 1.5 seconds
                    return Promise.resolve()
                }, 1500)
            } else { // Otherwise display an error to the user
                setTimeout(() => { // Dispatch an error state
                    dispatch(loginFailed("Incorrect email or password"))
                }, 1500)
            }
        } catch (err) { // When something goes wrong
            console.log(err)
            dispatch(loginFailed("Something went wrong"));
            return Promise.reject()
        }
    };
} // login
Run Code Online (Sandbox Code Playgroud)

然后我将它导入到我someComponent.js的导入actionCreator并使用bindActionCreators绑定它。

下面是这样的:

import { bindActionCreators } from "redux";
import * as authActions from "../actions/authenticate";
import { connect } from "react-redux";
Run Code Online (Sandbox Code Playgroud)

然后我将该操作连接到我的组件,即Login.js

export default connect(
    state => ({ state: state.authenticate }),
    dispatch => ({
        actions: bindActionCreators(authActions, dispatch)
    })
)(Login);
Run Code Online (Sandbox Code Playgroud)

所以我可以直接在 actionCreator 中调用函数 Login.js

下面是这样的:

onPress={() => {                                 
   this.props.actions.login(this.state.email, this.state.password)
}}
Run Code Online (Sandbox Code Playgroud)

但是我想要发生的是这个函数将调度一个redux 操作并在可能的情况下返回一个Promise

像这样的东西:

onPress={() => {                                 
       this.props.actions.login(this.state.email, this.state.password)
       .then(() => this.props.navigation.navigate('AuthScreen'))
    }}
Run Code Online (Sandbox Code Playgroud)

我想要发生的是当我尝试登录时。调度那些异步 redux thunk 操作并返回一个承诺。如果已解决,我可以重定向或导航到正确的屏幕。

感谢有人可以提供帮助。提前致谢。

小智 5

你的第一种方法大部分是正确的。dispatch(thunkAction())(或你的情况this.props.actions.login()恢复任何thunkAction()回报,所以它不会在情况下,它的回报承诺async

问题是 Promise 解决的问题,即您从async函数返回的任何内容。在您的情况下,无论凭据是否正确,您都不会等待setTimeout并返回void

因此,就异步功能而言,您需要类似的东西

export function login(email, password) { // Fake authentication function
    return async dispatch => {
        dispatch(loginRequest()); // dispatch a login request to update the state
        try {
            if (email.trim() === "test123@nomail.com" && password === "123456") { //If the email and password matches
                const session = { token: "abc1234", email: email, username: "test123" } // Create a fake token for authentication
                await AsyncStorage.setItem(DATA_SESSION, JSON.stringify(session)) // Stringinfy the session data and store it
                // Add a delay for faking a asynchronous
                await new Promise((resolve, reject) => setTimeout(() => resolve(), 1500));
                dispatch(loginSuccess(session));
                return Promise.resolve(true);
            } else { // Otherwise display an error to the user
                await new Promise((resolve, reject) => setTimeout(() => resolve(), 1500));
                dispatch(loginFailed("Incorrect email or password"))
                return Promise.resolve(false);
            }
        } catch (err) { // When something goes wrong
            console.log(err)
            dispatch(loginFailed("Something went wrong"));
            return Promise.reject()
        }
    };
} // login
Run Code Online (Sandbox Code Playgroud)

这样,您的异步函数将解析为true/ false,您可以在组件中使用它:

onPress={() => {                                 
       this.props.actions.login(this.state.email, this.state.password)
       .then((login_succeeded) => this.props.navigation.navigate('AuthScreen'))
    }}
Run Code Online (Sandbox Code Playgroud)

您也可以return dispatch(loginSuccess(session));(只要返回它的是 thunk 而不是setTimeout处理程序),在这种情况下,您的钩子中将loginSuccess(session)包含什么。.then()onPress