javascript - 如何设置其他函数内的值的状态
问题描述
我正在尝试创建一个使用 Clarifai API 检测图片年龄的 React 应用程序。我能够 Console.Log 检测到的年龄,但我想在我的网页上显示年龄。帮助我设置 AgeDect 状态,以便我可以在我的网页上使用它
//Value Displayed On Console
//39
</p>
//App.js Code That Console.Logs Age
class App extends Component {
constructor(){
super();
this.state = {
input : '',
imgURL : '',
AgeDetect : ''
}
}
onInputChange = (event) => {
this.setState({input : event.target.value});
}
onClickEvent = () => {
this.setState({imgURL : this.state.input})
app.models.predict(Clarifai.DEMOGRAPHICS_MODEL ,
this.state.input).then(
function(response) {
const A =response.outputs[0].data.regions[0].
data.face.age_appearance.concepts[0].name
//This Line of Code Displays Age on Console
console.log(A);
this.setState({AgeDetect : A});
},
//Having Problem SettingState ,this.state.AgeDetect isnt
//doing anything
render(){
return (<AgeDetection AgeDetect={this.state.AgeDetect}/>
)
}
//AgeDetection.js file
import React from 'react' ;
const AgeDetection = ({AgeDetect}) => {
return(
<div>
{AgeDetect}
</div>
);
}
export default AgeDetection;
解决方案
对由值返回的数组进行排序,并将第一个对象或整个数组设置为您的状态,然后您可以非常轻松地在应用程序中使用它。在 predict then 块中使用箭头函数绑定到类。
class App extends Component {
constructor() {
super();
this.state = {
input: '',
imgURL: '',
AgeDetect: ''
};
}
onInputChange = event => {
this.setState({ input: event.target.value });
};
onClickEvent = () => {
this.setState({ imgURL: this.state.input });
app.models.predict(Clarifai.DEMOGRAPHICS_MODEL, this.state.input).then(
response => {
const A =
response.outputs[0].data.regions[0].data.face.age_appearance
.concepts[0].name;
this.setState({ AgeDetect: A });
},
function(err) {
// there was an error
}
);
};
render() {
console.log(this.state);
return (
<div className='App'>
<Navigation />
<Logo />
<ImageLinkForm
onInputChange={this.onInputChange}
onClickEvent={this.onClickEvent}
/>
<FaceRecognition imgURL={this.state.imgURL} />
<AgeDetection AgeDetect={this.state.AgeDetect} />
</div>
);
}
}
export default App;
推荐阅读
- python-3.x - TypeError:需要一个类似字节的对象,而不是“协程”
- next.js - NextJS 在使用页面 API 时不断创建与 MongoDB 的新连接
- c# - 如何根据 MVC C# 中主图像或输出图像的大小增加或减少水印图像大小
- java - Leetcode #2,检测到循环错误
- javascript - npm WARN trumbowyg@2.21.0 需要 jQuery@>=1.8 的对等点,但没有安装。您必须自己安装对等依赖项
- javascript - 如何从选定的多边形切换填充颜色?
- r-markdown - RMarkdown:如何嵌入 3D 绘图?
- python - 从 America/New_York 时间到 UTC 并返回 America/New_York 的日期时间转换不正确
- java - Kafka Connect:将消息从字节转换为 Json
- c# - 更改正面尺寸会裁剪掉一些文本,即使 autosize 是正确的