开发者问题收集

React js 无法读取 API 调用属性未定义的属性“id”

2020-12-09
60

我正在开发一个 React 应用程序,该应用程序使用 Pixabay API 搜索并显示我搜索的主题的图片和视频。但是,当我尝试调用我获取的 API 调用的 id 时,我遇到了“无法读取未定义的属性‘id’”。我该怎么做才能修复此错误?

API 调用: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}] 0:{id:801826,pageURL:“https://pixabay.com/photos/pug-dog-pet-animal-puppy-cute-801826/”,type:“photo”,tags:“pug,dog,pet”,previewURL:“https://cdn.pixabay.com/photo/2015/06/08/15/02/pug-801826_150.jpg”,…} ...

import './App.css';
import React from 'react';
import Board from './board/board';
import ImageSearch from './imageSearch/imageSearch'

const API_KEY = "19435337-59a77b980b37e8c813d079adb"



class App extends React.Component {
state = {
    images: []
  }

  handleGetRequest = async (event) => {
    event.preventDefault();

    const searchValue = event.target.elements.searchValue.value;

    const URL = `https://pixabay.com/api/?key=${API_KEY}&q=${searchValue}&image_type=photo&per_page=7`
    
    const request = await fetch(URL);
    const response = await request.json();

    this.setState({ images : response.hits });
    console.log (this.state.images)
  }

  render() {
    return (
      <div>
        <ImageSearch handleGetRequest={this.handleGetRequest}/>
        <Board image={this.state.images[0]} />

      </div>

    )
  }
  
}

export default App;

Board.js

import './board.css';
import React from 'react';
  
const Board = (image) => {

  return ( 
    <div>
      <div key={image.image.id}>
        <input type="image" className="board__image" src={image.image.largeImageURL} alt={image.image.tags}></input>
      </div>
    </div>      
  )
}

export default Board;
1个回答

在 API 调用完成之前,结果不存在。您需要在 Board 组件中呈现标记之前检查它是否存在:

const Board = (image) => {

  return (
<> 
    { image && <div>
      <div key={image.image.id}>
        <input type="image" className="board__image" src={image.image.largeImageURL} alt={image.image.tags}></input>
      </div>
    </div> }    
</> 
  )
}

或者任何其他确保图像存在的解决方案都应该有效。

Chris B.
2020-12-09