【问题标题】:Rendering fetched data to screen将获取的数据渲染到屏幕上
【发布时间】:2018-11-27 15:02:58
【问题描述】:

我构建了一个组件,它使用 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>
    );
  }
}

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

先谢谢了。

【问题讨论】:

    标签: javascript reactjs react-component


    【解决方案1】:

    在您的渲染方法中,您可以映射 this.state.emails 并为每封电子邮件返回一个元素(起初数组将为空,因此您可以添加一个条件,这样您就不会无缘无故地渲染一个空的 div ) 类似:

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

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

    【讨论】:

    • 可爱的户田拉巴 :)
    • componentDidMount 是 React 中的一个保存词,表示该函数将在组件第一次挂载后运行。这意味着您不能自己触发该函数,因此您需要定义一个单独的类方法,您可以使用 this.YOUR_FUNCTION_NAME 调用它
    • 我明白了,我应该如何将其保留为按钮?
    • 我相信我不明白这个问题。您仍然可以拥有一个带有按钮的 div 和其中的电子邮件列表。
    • 你能看看我是如何编辑我的问题的吗?我把它放在一个按钮内,但现在当我点击它时,什么也没有发生..
    【解决方案2】:

    您使用了componentDidMount 生命周期来响应获取数据。你通过一个按钮调用了那个方法。通常我们不会像这样调用生命周期方法。我认为最好阅读 react 文档以了解生命周期。

    您可以声明一个函数并通过按钮调用该函数。请在下面找到答案。

    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          emails: [],
          showEmails:false,
        };
      }
    
      componentDidMount () {
        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.setState({showEmail:true})}>
             Get all mails
           </button>
           {this.state.showEmail && this.state.emails.map(email => <div>{email}</div>)}
         </div>
       );
     }
    }
    

    【讨论】:

    • 想坚持使用componentDidMount()怎么办?
    【解决方案3】:

    将您的代码更改为如下所示。

    您需要在单击按钮时收到电子邮件,因此您需要有自定义事件处理函数,但不需要 componentDidMount 方法。您不能将 componentDidMount 方法调用为事件处理函数。

    此外,当您在循环中呈现电子邮件时,您需要为循环内的顶部元素设置唯一键。键可以是数据中的索引或唯一 ID。看起来您没有电子邮件数组中的唯一 ID,因此您可以使用索引作为键,如下所示

         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: []
         }
    
      getEmails = () =>{
           //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>
                        <ul>
                          {this.state.emails.map((email, index)=> <li key={"Key-"+index}>{email}</li>)}
                         </ul>
                        <button type="button" onClick={()=> this.getEmails()}>Get all mails</button>
                    </div>
                     )
                }
             }
    

    【讨论】:

    • 想坚持使用componentDidMount()怎么办?
    • 在您的情况下,您不需要处理 componentDidMount。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多