如何将从API获取的值显示到ReactJS页面
让如何将从API获取的值显示到ReactJS页面,reactjs,api,Reactjs,Api,让resultofapi全局声明,我用从API收到的值初始化它。我想将该值显示到我的react js页面(在表中)。当我在API内部打印值时,它会返回我的输出{“相似性评分”:0.9999999404}。但是当我在API外部访问它时,它会给我value=undefine pd.usage() .then(response => { console.log(response); }) .catch(error => { console.log(error)
resultofapi
全局声明,我用从API收到的值初始化它。我想将该值显示到我的react js页面(在表中)。当我在API内部打印值时,它会返回我的输出{“相似性评分”:0.9999999404}
。但是当我在API外部访问它时,它会给我value=undefine
pd.usage()
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
**pd.semantic(
pd
.semantic(textarea1, textarea2)//these are forms data
.then(response => {
console.log(response); //output={"similarity_score":0.670276463}
*resultofapi = response;* //output=resultofapi={"similarity_score":0.670276463}*
})**
.catch(error => {
console.log(error);
})
)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
console.log(resultofapi)//output=undefined
创建一个state对象并使用API数据设置state。从那以后,你可以在你的全班访问它
this.state = {
items: []
};
componentDidMount() {
fetch("https://url.url.com")
.then(res => res.json())
.then(
(result) => {
this.setState({
items: result.items
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
return (
<ul>
{items.map(item => (
<li key={item.name}>
{item.name} {item.price}
</li>
))}
</ul>
);
this.state={
项目:[]
};
componentDidMount(){
取回(“https://url.url.com")
.then(res=>res.json())
.那么(
(结果)=>{
这是我的国家({
项目:result.items
});
},
//注意:这里处理错误很重要
//而不是一个catch()块,这样我们就不会吞咽
//组件中实际错误的例外情况。
(错误)=>{
这是我的国家({
isLoaded:是的,
错误
});
}
)
返回(
{items.map(item=>(
-
{item.name}{item.price}
))}
);