[英]How can I bind data from the API in react?
I'm new in React.JS.我是 React.JS 的新手。 I want to bind data from the API in a HTML code.
我想在 HTML 代码中绑定来自 API 的数据。
Here is a GET
method with axios from the API:这是 API 中带有 axios 的
GET
方法:
componentDidMount() {
var token = localStorage.getItem('accessToken');
var config = {
headers: { 'Authorization': "Bearer " + token }
};
var apiBaseUrl = "https://**********/";
const that = this;
axios.get(apiBaseUrl + 'api/Account/UserInfo', config)
.then(function (response) {
console.log(response.data);
if (response.status === 200) {
that.setState({ userInfo: response.data });
console.log(that.state.userInfo.Email);
}
else {
console.log(response.data);
}
})
.catch(function (error) {
console.log(error);
});
}
The console shows me控制台显示我
{Email: "xxxxxxx@yahoo.com", HasRegistered: true, LoginProvider: null}
Now I want to display the email address in HTML.现在我想在 HTML 中显示电子邮件地址。 How can I do this?
我怎样才能做到这一点?
Here you've set the state在这里你已经设置了状态
that.setState({ userInfo: response.data });
To access it - try this.state.userInfo.Email
要访问它 - 试试
this.state.userInfo.Email
You can put that into some html elements like this你可以把它放到一些像这样的html元素中
<p>{this.state.userInfo.Email}</p>
In JSX you can show like this在 JSX 中你可以这样显示
render(){
return (
<p>{this.state.userInfo ? this.state.userInfo.Email : 'Email is not provided'}</p>
)
}
in JSX you just define在 JSX 中,您只需定义
render(){
const email = this.state.userInfo? this.state.userInfo.Email:'';
return(
<div>{email}</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.