我正在尝试使用条件渲染来渲染类组件。类组件的状态值默认情况下设置为false。在该类中,名为start()
的函数执行某些操作,并根据结果调用具有verifyTheIdentity()
的函数setState()
。但是我无法从verifyTheIdentity()
呼叫start()
。
import React from "react";
import * as faceapi from "face-api.js";
import web3 from "../web3";
class recognize extends React.Component {
constructor(props) {
super();
this.state = {
verified: false
}
this.verifyTheIdentity = this.verifyTheIdentity.bind(this);
// this.start = this.start.bind(this);
}
verifyTheIdentity() {
this.setState(prevState => {
return {
verified: true
}
})
}
async start() {
///////////////////CODE FOR FACE RECOGNITION///////////////////////////////
let name = result.toString();
console.log(name);
const pattern = new RegExp(/^unknown/)
console.log(pattern.test(name))
if (pattern.test(name) === false) {
document.getElementById("verifier").disabled = false;
document.getElementById("verifier").onClick = this.verifyTheIdentity; //This is where I am going wrong.
}
else
document.getElementById("verifier").disabled = true;
})
})
}
render() {
return (
<div>
{this.state.verified == false ? <div><br /><br /><br /><br />
<input type="file" id="imageUpload" /><br />
<button disabled id="verifier" >Verify</button></div> :
<div><br /><br /><br /><br /><p>Verified</p></div>}
</div>
)
}
}
export default recognize;
这是我得到的错误。
Unhandled Rejection (TypeError): Cannot read property
'verifyTheIdentity' of undefined.
答案 0 :(得分:0)
首先,如果使用箭头功能,则根本不需要绑定。
constructor(props) {
super();
this.state = {
verified: false
}
}
verifyTheIdentity = () => {
//code
}
start = async () => {
// code
}
尝试一下,它应该可以工作。
或 删除注释的代码, 添加构造函数(从行中删除//)
this.start = this.start.bind(this);
答案 1 :(得分:0)
您可以在下面一行替换该行
document.getElementById("verifier").onClick = this.verifyTheIdentity;
像这样
document.getElementById("verifier").onClick = this.verifyTheIdentity();
答案 2 :(得分:0)
问题与Javascript语法违规有关-
“调用不带括号的函数”
要解决此问题,请使用以下正确语法调用函数verifyTheIdentity()
:
document.getElementById("verifier").onClick = this.verifyTheIdentity();
或者,将该函数分配给varialbe并调用它:
const test = verifyTheIdentity() {
this.setState(prevState => {
return {
verified: true
}
})
};
document.getElementById("verifier").onClick = this.test ;
为您的理解,请参见示例:
function Test(){
alert(1);
}
//Test; //It won't work
Test(); // It will work