reactjs - 无法在另一个函数中运行函数:无法读取未定义的属性“测试”/无法读取未定义的属性“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>
)
解决方案
您正在test
从 this.props 解构,并且该功能在道具中不存在。它只是您在组件中声明的一个函数。因此,您应该像这样将测试变量分配给测试函数:
const test = this.test
推荐阅读
- python - Python:创建一个幂等初始化器
- java - Java replaceAll 故障排除
- nginx - wos2 主动-主动多合一配置负载均衡器,带有 IIS 而非 NGINX
- pyqt5 - 日期时间对象 - 提取值
- android - Android 自定义组件调用 onClick 和 onLongClick 两次
- android - 如何在 x86 中使用 SIGRTMIN 或在 Android NDK 中使用 armeabi-v7a abi?
- ios - 如何检查设置iOS是否允许权限
- symfony - nginx 从 url 隐藏 symfony 语言环境
- java - XOR - 解释 3 行
- javascript - 如何删除带有条形标签的代码