无法在另一个函数中运行一个函数:无法读取未定义的属性“ test” /无法读取未定义的属性“ setState”

时间:2019-09-13 15:57:42

标签: reactjs

我想从onClose()函数运行一个回调test()。我试图在StackOverflow上找到解决方案,但无法解决问题。运行这段代码会给我带来带有代码块的注释中提到的未定义错误

constructor(props){
    super(props)
    this.state = {
      isPaid: false
    }
    this.test = this.test.bind(this)
  }
  test = () =>{
    const { isPaid } = this.state
    console.log(isPaid)
    this.setState({isPaid: true})
  }

  render() {
    const isPaid = this.state
    const {test} = this.props
    let config = {
      "publicKey": "*****",
      "productIdentity": "1234567890",
      "eventHandler": {
        onSuccess (payload) {
          console.log(payload);
        },
        onError (error) {
          // handle errors
          console.log(error);
        },
        onClose (){
          console.log('widget is closing');
          //Want to add some callback here to test()

          const {test} = this.props //The issue is here           
          console.log(test) //getting Undefined
          test(); //TypeError: Cannot read property 'test' of undefined


          //OR

          console.log(isPaid) //I get state as log
          this.setState({isPaid: !isPaid}) //TypeError: Cannot read property 'setState' of undefined

        }
      }
    };
    let checkout = new paygateway(config);
    return (
      <div>
        <button onClick={ () => {checkout.show({amount: 1000})} }>Test</button>

      </div>
    )

1 个答案:

答案 0 :(得分:3)

您正在从this.props解构test,而该函数在props中不存在。这只是您在组件中声明的函数。因此,您应该像这样将测试变量分配给测试函数:

const test = this.test