ReactJS -相同的方法,不同的结果



我正在学习React,在遵循教程的同时,我想知道为什么#1方法没有console.log任何东西,而#2方法却有。有人能解释一下为什么吗?

calculateFaceLocation = (data) => {
return (console.log(data.outputs[0].data.regions[0].region_info.bounding_box));
}
//DOESN'T WORK
onButtonSubmit = () => {
this.setState({imageUrl: this.state.input})
app.models.predict(Clarifai.FACE_DETECT_MODEL, this.state.input).then(
function (response) {
this.calculateFaceLocation(response);
}
)
}
//WORKS
onButtonSubmit = () => {
this.setState({imageUrl: this.state.input})
app.models.predict(Clarifai.FACE_DETECT_MODEL, this.state.input).then(response => this.calculateFaceLocation(response)).catch(err=> console.log(err));
}

在#1函数中,您给.then()一个常规函数,因此当它调用

this.calculateFaceLocation(response);

this对象没有calculateFaceLocation()方法,它在你的react类中定义,而this对象包含窗口对象。

但是对于你的#2函数,你正在使用箭头函数,这就是为什么你在这里得到你的控制台日志值。因为在箭头函数中,它没有自己的this,而是从父节点获取。

阅读更多关于箭头函数

我在两个函数中都添加了console.log(this);。现在运行这段代码并检查控制台,您将看到差异。


calculateFaceLocation = (data) => {
return (console.log(data.outputs[0].data.regions[0].region_info.bounding_box));
}
//DOESN'T WORK
onButtonSubmit = () => {
this.setState({ imageUrl: this.state.input })
app.models.predict(Clarifai.FACE_DETECT_MODEL, this.state.input).then(
function (response) {
console.log(this);
this.calculateFaceLocation(response);
}
)
}
//WORKS
onButtonSubmit = () => {
this.setState({ imageUrl: this.state.input })
app.models.predict(Clarifai.FACE_DETECT_MODEL, this.state.input).then(
response => {
console.log(this);
this.calculateFaceLocation(response);            
}
).catch(err => console.log(err));
}

最新更新