.then()在React-Native中未定义

时间:2018-06-13 20:26:19

标签: typescript redux

我使用的是Typescript,React和Redux。我无法理解为什么函数 .then()不能处理我的 Promise 函数。所有这些代码在一个简单的 React (非Native)应用程序中运行得非常好。

接口:

export interface IAuthenticationSigninAction extends AnyAction {
    error?: boolean;
    payload: {
        userEmail: string;
        userPassword: string;
        isAuthenticated?: boolean;
    };
}

reducer中的函数(非reducer函数。没关系):

export function authenticationSignin(email: string, password: string): 
IAuthenticationSigninAction {
    return {
        type: AUTHENTICATION_SIGNIN_RESPONSE,
        payload: {
            userEmail: email,
            userPassword: password
        }
    }
}

容器中的调度:

export interface IDispatchProps {
        authenticationSignin: (email: string, password: string) => Promise<IAuthenticationSignin>;
    }
function mapDispatchToProps(dispatch: any) {
    return {
        authenticationSignin: (email: string, password: string): Promise<IAuthenticationSignin> => dispatch(authenticationSignin(email, password))
    };
}

最后,由于 .then()而崩溃的代码:

handleSignIn() {
        this.props.authenticationSignin(this.state.email, this.state.password).then((response) => {
            console.log(response.isAuthenticated);
        });
    }

错误: **

  

undefined不是一个函数(评估   &#39; this.props.authenticationSignin(this.state.email,   this.state.password).then(function(response){       的console.log(response.isAuthenticated); })&#39)

**

As per my function signature, I compare to fetch which is undoubtedly a promise and they're identical minus the obvious changes.

任何人都有关于如何处理这个问题的建议吗?提前谢谢。

1 个答案:

答案 0 :(得分:1)

在评论中的讨论中,这是一个返回承诺的thunk动作创建者看起来像:

export function someThunkReturningAPromise() {
    return (dispatch, getState) => {
        const promise = someAjaxLib.fetchSomeData();

        // could also do some dispatching in here, or anything else you want

        // this is the important part
        return promise;
    }
}

// later, in a component file:

import {someThunkReturningAPromise} from "./actions";

const actionCreators = {someThunkReturningAPromise};

class MyComponent extends Component {
    handleClick = () => {
        this.props.someThunkReturningAPromise()
           .then( () => {
               // this is only possible because the thunk action creator
               // returned a promise
           });
    }
}

export default connect(null, actionCreators)(MyComponent);