gpt4 book ai didi

reactjs - 无法在另一个函数内运行一个函数: Cannot read property 'test' of undefined/Cannot read property 'setState' of undefined

转载 作者:行者123 更新时间:2023-12-03 14:11:20 25 4
gpt4 key购买 nike

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

关于reactjs - 无法在另一个函数内运行一个函数: Cannot read property 'test' of undefined/Cannot read property 'setState' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57926888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com