首页 > 解决方案 > 无法在另一个函数中运行函数:无法读取未定义的属性“测试”/无法读取未定义的属性“setState”

问题描述

我想从 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>
    )

标签: reactjs

解决方案


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

const test = this.test

推荐阅读