当我尝试传入从 API 请求中获取的 JSON 对象时,React Hook useState 不起作用

问题描述 投票:0回答:1

错误 无法读取未定义的属性(读取“排名”) 类型错误:无法读取未定义的属性(读取“排名”) 在 MovieCard (http://localhost:3000/static/js/bundle.js:250:44) 在 renderWithHooks (http://localhost:3000/static/js/bundle.js:21333:22) 在 mountIndeterminateComponent (http://localhost:3000/static/js/bundle.js:24619:17) 在 beginWork (http://localhost:3000/static/js/bundle.js:25915:20) 在 HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:10925:18) 在 Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:10969:20) 在 invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:11026:35) 在 beginWork$1 (http://localhost:3000/static/js/bundle.js:30900:11) 在 performUnitOfWork (http://localhost:3000/static/js/bundle.js:30147:16) 在 workLoopSync (http://localhost:3000/static/js/bundle.js:30070:9)

我的应用程序.jsx

import React, { useEffect, useState} from "react";
// import axios from "axios";
import "./App.css";
import SearchIcon from './search.svg';
import MovieCard from "./MovieCard";



const API_URL = 'https://anime-db.p.rapidapi.com/anime?page=1&size=10';
const options = {
    method: 'GET',
    headers: {
        'X-RapidAPI-Key': '86f93f3665msh3f8b81058a26p1a3effjsnfgg0c6ff789ce',
        'X-RapidAPI-Host': 'anime-db.p.rapidapi.com'
    }
};


const App = () => {
  const [anime,setAnime] = useState([]);
  const searchAnime =  async (title)=>{
  const response = await fetch(`${API_URL}&search=${title}`,options);
  const data =await response.json();
  console.log(data);
  data.then(function(res){
    setAnime(res.data)
  })
  }
  
  useEffect(()=>{
    searchAnime("shigatsu");
  },[])

  return (<div className="app">
    <h1>
      Annie-Plex
    </h1>
    <div className="search">
      <input placeholder="Search for Anime" value = "" onChange={()=>{}}/>
      <img
      src={SearchIcon}
      alt="Search"
      onClick={()=>{}}
      />

    </div>
    <div className="container">
      <MovieCard
      M1 = {anime[0]}/>           //this part gives the error

    </div>
  </div>);
};

export default App;

我的电影卡.js

import React from 'react'

const MovieCard = ({M1}) => {
  return (
    <div className="movie">
    <div>
      <p>Current Ranking: {M1.ranking}</p>
    </div>
    <div>
      <img src={M1.image} alt={M1.title} />
    </div>
    <div>
      <span>{M1.type}</span>
      <h3>{M1.title}</h3>
    </div>
  </div>


  )
}

export default MovieCard    

我期待加载请求的第一张卡片

javascript reactjs react-hooks
1个回答
0
投票

在请求完成并且数组中确实有第一个元素之前不要显示组件。

{anime[0] && <MovieCard M1={anime[0]}/>}

另外,不要在已经被

.then
ed的值上使用
await
(它不是
Promise
)。如果返回的 JSON 是一个数组,那么你应该简单地调用
setAnime(data);
.

© www.soinside.com 2019 - 2024. All rights reserved.