gpt4 book ai didi

javascript - 将获取的数据渲染到屏幕

转载 作者:行者123 更新时间:2023-11-30 09:18:14 24 4
gpt4 key购买 nike

我构建了一个使用 Axios 获取请求并检索电子邮件地址列表的组件。

我不知道我应该在 render() 中写什么,这样我才能在我的网站上看到电子邮件列表。

这是我的建议:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {Link} from "react-router";
import axios from 'axios';

export class GetEmailsComponent extends Component {

state = {
emails: []
}

componentDidMount(){
//this.setState({emailList : undefined});
axios.get('./api/EmailAddresses')
.then(response => {
this.setState({emails: response.data});
console.log(response.data);
}).catch(function (error) {
console.log(error);
});
}

render() {
return (
<div>
<button type = "button" onClick= {this.state.emails.map(email => <div>{email}</div>)}>GET ALL EMAILS</button>
</div>
);
}
}

当我检查控制台时,我会看到一组所需的电子邮件。我正在寻找有关如何编辑我的代码的建议,以便它将所有这些邮件呈现到屏幕上(单击按钮后)。

提前致谢

最佳答案

在你的 render 方法中,你可以映射 this.state.emails 并为每封电子邮件返回一个元素(起初数组是空的,所以你可以添加一个条件,这样你就不会'无缘无故地呈现一个空的 div)像这样:

render() {
return (
<div>
{this.state.emails.map(email => <div>{email}</div>)}
</div>
);
}

至于 componentDidMount - 它是 React 的一个生命周期方法。你放在那里的任何东西都会在组件第一次安装后运行。如果您想在单击按钮后触发对 Axios 的调用,请定义一个不同的函数(如 fetchEmails)并使用 this.fetchEmails 调用它。

关于javascript - 将获取的数据渲染到屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53502484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com