【问题标题】:Async Await with SetState... am I doing this right?Async Await with SetState ...我这样做对吗?
【发布时间】:2020-02-21 16:00:55
【问题描述】:

如果没有保存一张卡片,我正在尝试让用户添加一张卡片,如果用户添加了一张卡片,请禁用该按钮并告诉它我将使用已保存的卡片。

通过tipsi-stripe获取token的方式是通过await。难道我做错了什么?也许我不完全理解这个概念?

export default class NewCardPage extends Component {
  constructor(props){
    super(props)
    this.state = {
      gotToken: false,
    };
  }

  render() {
    async function paymentRequestWithCardForm() {
      const options = {
        prefilledInformation: {
            email: 'jane.doe@outlook.com',
        },
      }
      try {
        const token = await stripe.paymentRequestWithCardForm(options)
        if (token){this.setState({ gotToken:true });} 
        else {this.setState({ gotToken:false });}
      }
      catch(err) {
        console.log(err.code)
        {this.setState({ gotToken:false });}
      }
    }

    return(
    <View style={styles.buttonContainer}>
      {this.state.gotToken === false ? <Button title='Add a Credit Card' style={styles.buttonStyle} onPress={() => { paymentRequestWithCardForm() }}></Button> : <Button disabled={true} title='Using saved credit card' style={styles.buttonStyle}></Button> }
    </View>
    )
  }
}

【问题讨论】:

  • render 中有paymentRequestWithCardForm 不是一个好主意
  • 虽然您应该将回调绑定到您的组件实例,但乍一看这应该仍然有效。是否发生任何错误?行为与期望的行为有何不同?任何错误信息?
  • @Taki 我把它移到了渲染之外。取出函数这个词并编辑paymentRequestWithCardFormthis.paymentRequestWithCardForm @trixn 我认为这是Taki 提到的。可能命令,我也虽然我做的是正确的事情。

标签: javascript reactjs react-native async-await asynchronous-javascript


【解决方案1】:

这是一种常见的模式,但是将函数定义为类属性会更有效(这样就不会在每次渲染时都创建它):

export default class NewCardPage extends Component {
  state = {
      gotToken: false,
    }

  paymentRequestWithCardForm = aync() => {
      const options = {
        prefilledInformation: {
            email: 'jane.doe@outlook.com',
        },
      }
      try {
        const token = await stripe.paymentRequestWithCardForm(options)
        if (token){this.setState({ gotToken:true });} 
        else {this.setState({ gotToken:false });}
      }
      catch(err) {
        console.log(err.code)
        {this.setState({ gotToken:false });}
      }
    }

  render() {

    return(
    <View style={styles.buttonContainer}>
      {this.state.gotToken === false ? <Button title='Add a Credit Card' style={styles.buttonStyle} onPress={this.paymentRequestWithCardForm}></Button> : <Button disabled={true} title='Using saved credit card' style={styles.buttonStyle}></Button> }
    </View>
    )
  }
}

【讨论】:

    猜你喜欢
    • 2012-08-13
    • 2023-03-19
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 2016-06-02
    • 2015-01-13
    • 2021-06-05
    • 2021-07-30
    相关资源
    最近更新 更多