繁体   English   中英

如何在反应中绑定来自 API 的数据?

[英]How can I bind data from the API in react?

我是 React.JS 的新手。 我想在 HTML 代码中绑定来自 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);
        });
}

控制台显示我

{Email: "xxxxxxx@yahoo.com", HasRegistered: true, LoginProvider: null}

现在我想在 HTML 中显示电子邮件地址。 我怎样才能做到这一点?

在这里你已经设置了状态

 that.setState({ userInfo: response.data });

要访问它 - 试试this.state.userInfo.Email

你可以把它放到一些像这样的html元素中

<p>{this.state.userInfo.Email}</p>

在 JSX 中你可以这样显示

render(){
  return (
    <p>{this.state.userInfo ? this.state.userInfo.Email : 'Email is not provided'}</p>
  )
}

在 JSX 中,您只需定义

render(){
const email = this.state.userInfo? this.state.userInfo.Email:'';
return(
  <div>{email}</div>
 )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM