【问题标题】:Foreach loop in return statement of reactreact的return语句中的foreach循环
【发布时间】:2019-07-28 09:32:15
【问题描述】:

我已经从 API 中获取了一些信息,现在我正在尝试显示从中获取的信息。我获取的信息包括 books_authors 、 books_id's 、 price ,并且数据集非常大,我无法通过以下方法显示这些信息......有人可以帮我解决这个问题......我是新来的反应

这是我迄今为止尝试过的:

import React from "react";
import Head from './head';

function App(){

  let s;
  const proxy = 'http://cors-anywhere.herokuapp.com/';
  const api = `${proxy}http://starlord.hackerearth.com/books`;
  fetch(api)
  .then(response =>{
    return response.json();
  })
  .then(data =>{
    console.log(data);
    data.forEach((index) => {
       s=index;
      <Head s/>
    });
  });
  return(
    <Head />
  );
}

export default App;


//the head component


import React from "react";

function Head(props){

    return(
        <div className="app">
            <div className="heading">
                <h1>BOOK_CAVE</h1>
                <div className="heading_description">So many books...so 
little time...</div>
            </div>
            <div className="author">{props.authors}</div>
            <div className="id">{props.bookID}</div>
            <div className="price">{props.price}</div>
        </div>
    );
}

export default Head;

【问题讨论】:

    标签: javascript reactjs foreach


    【解决方案1】:

    您可以使用HooksuseState 存储数据并使用useEffect 调用API 来执行此操作,

    import React, {useState,useEffect} from "react";
    import Head from './head';
    
    function App(){
      const [data, setData] = useState([])
    
      useEffect(() => {
          const proxy = 'http://cors-anywhere.herokuapp.com/';
          const api = `${proxy}http://starlord.hackerearth.com/books`;
          fetch(api).then(response => {
            setData(response.json())
          })
        },[])
    
    
      return(
        <div>
          {data.length>0 && data.map(book => <Head book={book} />)
        </div>
      );
    }
    

    而你的 Head 组件应该是,

    function Head(props){
    
        return(
            <div className="app">
                <div className="heading">
                    <h1>BOOK_CAVE</h1>
                    <div className="heading_description">So many books...so 
    little time...</div>
                </div>
                <div className="author">{props.book.authors}</div>
                <div className="id">{props.book.bookID}</div>
                <div className="price">{props.book.price}</div>
            </div>
        );
    }
    

    【讨论】:

      【解决方案2】:

      您从 API 获取的书籍数组应该存储在一个状态中,并且您应该根据该状态呈现应用程序。数据获取应该在组件挂载时发生,因此您调用 componentDidMount 生命周期方法,并在数据获取完成时更新状态。此外,Head 组件接收三个 props,但您只传递了一个。

      class App extends React.Component {
          constructor(props) {
            super(props);
            this.state = {
              books: [],
              fetching: true,
          }
      
          componentDidMount() {
            const proxy = 'http://cors-anywhere.herokuapp.com/';
            const api = `${proxy}http://starlord.hackerearth.com/books`;
            fetch(api)
              .then(response => response.json() )
              .then(data => this.setState({books: data, fetching: false,}) );
          }
      
          render() {
            if (this.state.fetching) {
              return <div>Loading...</div>
            }
      
            const headArray = this.state.books.map(book => (
              <Head
                  authors={book.authors}
                  bookID={book.bookID}
                  price={book.price}
              />
            ));
      
            return(
              <div>
                {headArray}
              </div>
            ); 
          }
      }
      

      【讨论】:

        【解决方案3】:

        你需要:

        1. fetch 包含在生命周期方法或useEffect 挂钩中

        2. 将 API 的响应置于某种状态(这将导致重新渲染)

        3. 迭代return 语句中的状态,使用map,而不是forEach

        使用钩子的示例:

        function App(){
          const [apiData, setApiData] = useState([])
          const [isLoading, setIsLoading] = useState(true)
        
          useEffect(
            () => {
              const proxy = 'http://cors-anywhere.herokuapp.com/';
              const api = `${proxy}http://starlord.hackerearth.com/books`;
              fetch(api).then(response => {
                setApiData(response.json())
                setIsLoading(false)
              })
            },
            []
          )
        
          const authors = data.map((index) => index.authors).flat()
        
          return(
            <div>
              {authors.map((author) => <Head author{author} />)
            </div>
          );
        }
        

        【讨论】:

        • @Mattieu 我已经对代码的 部分进行了一些更改(现在我将整个索引作为参数设置为它)...它将对解决方案产生什么影响你给我的……
        • 您可以将{authors.map((author) =&gt; &lt;Head author{author} /&gt;) 替换为{data.map((index) =&gt; &lt;Head {...index} /&gt;)
        • 那是apiData,不是data,我的错
        猜你喜欢
        • 2011-08-17
        • 2014-08-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-07
        相关资源
        最近更新 更多