簡體   English   中英

'pic' 沒有被 React 定義

[英]'pic' is not defline with React

我正在開展一個學校項目,該項目是關於創建一個網站,顯示一個帶有 Flickr API 的照片庫(在這種情況下為 Photo.search)我正在努力解決說“圖片未定義”的錯誤。 我不知道在這種情況下該怎么辦。 我會很高興收到任何幫助來解鎖我。 提前致謝 !

import React, { Component } from 'react';
import './App.css';




class App extends Component {
  constructor(){
    super();
    this.state = {
      pictures: [],
      page: 1,
      total_pages: -1 
      
    };
  }

  renderPhotos(){
    
    console.log(
      this.state.pictures
    )

     return(
    
      <div>

    this.state.pictures.map((pic) => {
        
    <img className="img-thumbnail m-2" src={'https://farm'+pic.farm+'.staticflickr.com/'+pic.server+'/'+pic.id+'_'+pic.secret+'_w.jpg'} alt="bike" />
      
    })

    </div>

    )
  }

  componentDidMount(){
    alert(process.env.REACT_APP_API_KEY);
    fetch('  https://www.flickr.com/services/rest/?method=flickr.photos.search&api_key={APIKEY}_id=&tags=bikerace%2Cboulderbiketour&per_page=42&page=1&format=json&nojsoncallback=1')
    .then(function(response){
      return response.json();
    })
    .then(function(j){

      alert(JSON.stringify(j));
      if (this.state.total_pages == -1){
        this.setState({total_pages: j.photos.pages,pictures: j.photos.photo})
      }
      else{ 
        this.setState({pictures: j.photos.photo})
      }

      
     
    })
  }

  NextPage = () => {
   var CurrentPage = this.state.page;
   CurrentPage++;
   if (CurrentPage <= this.state.total_pages){
    this.setState({page:CurrentPage});
   }
   

  }

 
  PreviousPage = () => {
    var CurrentPage = this.state.page;
    CurrentPage--; 
    if (CurrentPage >= 1){
      this.setState({page:CurrentPage});
     }

    
 
   }
 

  render() {
    return (
      <div className="App">
        <header className="App-header">
        
          <h1 className="App-title">Welcome to React</h1>
          
        </header>
         
        <p>
          <div>
           Page {this.state.page}
          </div>
          
            <div className="gallery p-5">
          
          {this.renderPhotos()}

          </div>

          <div>

          <button onClick={this.PreviousPage}>Previous</button>
          <button onClick={this.NextPage}>Next</button>
          </div>
          

        </p>

        
      </div>
    );
  }
}

export default App;

老實說,這里沒有很多關於 go 的信息,但只是通過查看代碼,我看到了我經常遇到的一些事情。 React 在渲染項目時很有趣,因為它會渲染,然后更新 state,然后再次渲染。 這與如果任何未定義的內容 React 只會崩潰的事實相混合,這意味着它將在第一次渲染之前崩潰,然后再進行第二次渲染。 如果您嘗試將其注銷,您將在控制台日志中看到這一點。 反應組件中通常有多個渲染,如果任何渲染中未定義任何內容。 React 只會崩潰。

在您的情況下,React 會在此之前檢查 map。state.pictures 已定義,因此它在進入第二個渲染之前崩潰。 這是您解決此問題的方法。

  1. Console.log(this.state)
  2. 如果可行,那么 console.log(this.state.pictures)
  3. 繼續下線,直到它崩潰。
  4. 在崩潰的時候做一個心理記錄。 假設它在“this.state.pictures”處崩潰。 然后,您將要在下面編寫以下代碼

this.state && this.state.pictures.map(pic)

這需要整本教科書來解釋為什么會這樣,但確實如此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM