API成功后,回调未正确调用?

时间:2018-06-05 08:51:56

标签: javascript reactjs ternary-operator

handleSubmit = ev => {

     ev.preventDefault();
     this.props.stripe.createToken().then(payload => {
       let data = {
            currency: 'USD',
            amount: localStorage.getItem("price"),
            source: payload.token.id,
            description: 'xyz'
        }
        PlanAction._stripecharge(data, function(data){

            let data1 = {
                username: localStorage.getItem('username'),
                plan: {
                    id: this.props.request.id,
                    planName: this.props.request.planName,
                    planType: this.props.request.planType
                    }

            }
            data.paid ? PlanAction._createUserPlan(data1) : null
        });

    });
 }

成功完成条纹冲锋后, 我得到了回应:真实

如果支付是真的,我正在使用三元运算符

data.paid  ? PlanAction._createUserPlan(data1) : null

这是错的吗? 为什么没有调用PlanAction._createUserPlan(data1)我可能知道这个错误

export function _stripecharge(data,callback) {
let url = "/charges";
 let BASE = "https://api.stripe.com/v1"
 let actualurl = BASE + url;

 stripeApi._callAPI(actualurl, 'POST', data, (type, dt) => {
     if (type == 'success') {
        dispatcher.dispatch({
            type: 'SnackBar',
            string: "Payment Success" 
        })

        callback(dt);

     } 

 });

}

2 个答案:

答案 0 :(得分:3)

我猜data.paidtrue,而不是"true",所以改动很小:

data.paid ? PlanAction._createUserPlan(data1) : null

但严重的是,这是if声明的用语:

if (data.paid) PlanAction._createUserPlan(data1);

旁注:您既不会处理来自this.props.stripe.createToken()的错误,也不会将承诺传递给来电者。你必须做一个或另一个。根据事实,这看起来像一个DOM事件处理程序,你想要处理错误(例如,通过.catch),而不是传递承诺。

答案 1 :(得分:0)

尝试在data.paid上使用if语句

handleSubmit = ev => {

     ev.preventDefault();
     this.props.stripe.createToken().then(payload => {
       let data = {
            currency: 'USD',
            amount: localStorage.getItem("price"),
            source: payload.token.id,
            description: 'xyz'
        }
        PlanAction._stripecharge(data, function(data){

            let data1 = {
                username: localStorage.getItem('username'),
                plan: {
                    id: this.props.request.id,
                    planName: this.props.request.planName,
                    planType: this.props.request.planType
                    }

            }

            if(data.paid){
               PlanAction._createUserPlan(data1) 
            } else {
               null
            }

        });

    });
 }