【问题标题】:How to show success message if data is fetched successfully in console.log?如果在 console.log 中成功获取数据,如何显示成功消息?
【发布时间】:2019-09-07 21:11:22
【问题描述】:

我在 react-native 中使用条带库,我在 console.log 中成功获取数据,但是如果成功,或者如果它有任何错误,我想重定向到另一个页面,然后显示在页面上。我试图重定向到另一个页面,但即使它有错误,它也会重定向,我不知道该怎么做。我试过这样做..

这是我的代码。

    payme() {
            const apiKey = '<api_key>';
            const client = new Stripe(apiKey);
            client.createToken({
                number: this.state.number,
                exp_month: this.state.expmonth,
                exp_year: this.state.expyear,
                cvc: this.state.cvc,
            }).then((x) => {
                    let successmsg = x;
                    NavigationService.navigate('LoginPage');
            }).catch((e) => {
                console.log(e);
            })
        }

    render() {
            return (
              <Text>{this.successmsg}</Text>
            )
    }

谁能帮助我了解如何显示错误以及如何仅在成功时重定向到其他页面。

【问题讨论】:

  • 这是哪里。 successmsg() ??
  • 使用this.setState({ response: x })并使用渲染函数中的状态{this.state.response}

标签: reactjs api react-native fetch stripe-payments


【解决方案1】:

根据您的代码,您将在 this.successmsg 中收到错误

    state = {
     successmsg : null          
    }

    async payme() {
            try{
                   const apiKey = '<api_key>';
                   await result  = new Stripe(apiKey).createToken({
                   number: this.state.number,
                   exp_month: this.state.expmonth,
                   exp_year: this.state.expyear,
                   cvc: this.state.cvc,
                   })

                   if(!result.error){
                      //do your success logic
                     //set your successmsg based on reslut object option
                      this.setState({successmsg : "YOURCUSTOM MESSAGE FROM RESULT OBJECT"})
                      NavigationService.navigate('LoginPage');

                   } else {
                      // throw your error here
                        throw "something went wrong"
                    }

             }
             catch(e){
              throw new Error(e);
             }

        }

    render() {
            return (
              <Text>{this.successmsg}</Text>
            )
    }

【讨论】:

  • 它向我显示 if(result){this.setState({})} 中的错误...这是错误的地方
  • 在代码中查看上面的截图。我在 if(result){} 中做了控制台
  • 您从服务器使用的状态代码是什么...如果您使用 200,那是您收到错误响应的地方。
  • 是什么意思?我没有从服务器得到那个状态码?
猜你喜欢
  • 1970-01-01
  • 2017-03-21
  • 1970-01-01
  • 2011-08-07
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
相关资源
最近更新 更多