无法在另一个函数中运行一个函数:无法读取未定义的属性'test'/无法读取未定义的属性'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>
)

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

const test = this.test

相关内容

  • 没有找到相关文章

最新更新