【问题标题】:How can I display all the objects of array from fetch in div?如何在 div 中显示 fetch 中的所有数组对象?
【发布时间】:2021-01-20 10:27:30
【问题描述】:

如何以正确的方式保存我的对象数组?然后在html中显示它们? 控制台日志可以打印整个数组,但在 html 中的工作方式不同

import React from "react";
import "./style.css";
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      quotes: [],
    };
  }

  componentDidMount() {
    fetch("https://type.fit/api/quotes")
      .then((response) => response.json())
      .then((data) => this.setState({ quotes: data }));
  }

  render() {
    console.log(this.state.quotes.text);
    return (
      <div>
        <h1>{this.state.quotes[0].author}</h1>
      </div>
    );
  }
}

export default App;

【问题讨论】:

标签: javascript reactjs react-native fetch


【解决方案1】:

您可以通过 JSX 中的引号进行映射。

return (
   <div>
     {this.state.quotes && this.state.quotes.map(quote => (
       <div>
         <h1>{quote.author}</h1>
         <p>{quote.content}</p>
       </div>
     ))}
   </div>
 );

如果我误解了什么或者有什么帮助,请告诉我:)

【讨论】:

  • 哦,我忘了关闭括号 :) 查看编辑后的答案。
  • 如果我想同时打印姓名和文字,我需要映射两次吗?
  • 不,您可以添加另一个 jsx 标签检查已编辑的答案
  • 太棒了……看起来太棒了:)
【解决方案2】:

这样做:

const quotes = this.state.quotes.map((quote) => {
      return (
          <div>
              <h1>{quote.author}</h1>
          </div>
      );
    });

然后在你的主要组件的 return 中使用这个 quotes,如下所示:

return(
    <div>{quotes}</div>
)

【讨论】:

    【解决方案3】:

    你可以这样使用:

    import React from "react";
    import "./style.css";
    class App extends React.Component {
      constructor() {
     super();
     this.state = {
       quotes : []
     };
    }
    
      componentDidMount() {
      fetch("https://type.fit/api/quotes")
       .then((response) => response.json())
       .then((data) => this.setState({ quotes: data }))
    }
    
     render() {
     console.log(this.state.quotes.text)
     return (
      
       <div>
         {this.state.quotes ?
          {this.state.quotes.map(quotes.author=> (
            <h1>{author}</h1>
          ))}
         :
         <h1>{"Not loaded"}</h1>
         }
       </div>
     );
     }
     }
    

    【讨论】:

      【解决方案4】:

      使用Array.prototype.map 生成jsx 元素。在渲染方法中:

      render() {
          retrun(
          {this.state.quotes.map(quote => (
               <div>
                    <h2>{qutoe.author}<h2>
               </div>
          ))}
         )
      }
      

      【讨论】:

        猜你喜欢
        • 2013-03-13
        • 1970-01-01
        • 1970-01-01
        • 2015-01-28
        • 2019-02-27
        • 2019-09-29
        • 2021-10-26
        • 2012-06-30
        • 1970-01-01
        相关资源
        最近更新 更多