React Hook useState在我尝试传入从API请求获取的JSON对象时无法工作。

huangapple go评论65阅读模式
英文:

React Hook useState doesnt work when I try passing in a JSON object fetched from an API request

问题

错误:

无法读取未定义的属性(读取 'ranking')
类型错误:无法读取未定义的属性(读取 'ranking')
在 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) 中


我的 app.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="搜索动漫" value = "" onChange={()=>{}}/>
<img
src={SearchIcon}
alt="搜索"
onClick={()=>{}}
/>
</div>
<div className="container">
<MovieCard
M1 = {anime[0]}/> //此部分出现错误

&lt;/div&gt;

</div>);
};

export default App;




我的 moviecard.js

import React from "react";

const MovieCard = ({M1}) => {
return (
<div className="movie">
<div>
<p>当前排名: {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;


我期望能加载请求的第一张卡片。
英文:

Error:

Cannot read properties of undefined (reading &#39;ranking&#39;)
TypeError: Cannot read properties of undefined (reading &#39;ranking&#39;)
    at MovieCard (http://localhost:3000/static/js/bundle.js:250:44)
    at renderWithHooks (http://localhost:3000/static/js/bundle.js:21333:22)
    at mountIndeterminateComponent (http://localhost:3000/static/js/bundle.js:24619:17)
    at beginWork (http://localhost:3000/static/js/bundle.js:25915:20)
    at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:10925:18)
    at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:10969:20)
    at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:11026:35)
    at beginWork$1 (http://localhost:3000/static/js/bundle.js:30900:11)
    at performUnitOfWork (http://localhost:3000/static/js/bundle.js:30147:16)
    at workLoopSync (http://localhost:3000/static/js/bundle.js:30070:9)

My app.jsx

import React, { useEffect, useState} from &quot;react&quot;;
// import axios from &quot;axios&quot;;
import &quot;./App.css&quot;;
import SearchIcon from &#39;./search.svg&#39;;
import MovieCard from &quot;./MovieCard&quot;;



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


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

  return (&lt;div className=&quot;app&quot;&gt;
    &lt;h1&gt;
      Annie-Plex
    &lt;/h1&gt;
    &lt;div className=&quot;search&quot;&gt;
      &lt;input placeholder=&quot;Search for Anime&quot; value = &quot;&quot; onChange={()=&gt;{}}/&gt;
      &lt;img
      src={SearchIcon}
      alt=&quot;Search&quot;
      onClick={()=&gt;{}}
      /&gt;
    &lt;/div&gt;
    &lt;div className=&quot;container&quot;&gt;
      &lt;MovieCard
      M1 = {anime[0]}/&gt;           //this part gives the error

    &lt;/div&gt;
  &lt;/div&gt;);
};

export default App;

my moviecard.js

import React from &#39;react&#39;

const MovieCard = ({M1}) =&gt; {
  return (
    &lt;div className=&quot;movie&quot;&gt;
    &lt;div&gt;
      &lt;p&gt;Current Ranking: {M1.ranking}&lt;/p&gt;
    &lt;/div&gt;
    &lt;div&gt;
      &lt;img src={M1.image} alt={M1.title} /&gt;
    &lt;/div&gt;
    &lt;div&gt;
      &lt;span&gt;{M1.type}&lt;/span&gt;
      &lt;h3&gt;{M1.title}&lt;/h3&gt;
    &lt;/div&gt;
  &lt;/div&gt;


  )
}

export default MovieCard    

I was expecting the first card of the request to be loaded up

答案1

得分: 1

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

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

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

英文:

Don't display the component until the request has been completed and there actually is a first element in the array.

{anime[0] &amp;&amp; &lt;MovieCard M1={anime[0]}/&gt;}

Also, don't use .then on a value that has already been awaited (it's not a Promise). If the returned JSON is an array, then you should simply call setAnime(data);.

huangapple
  • 本文由 发表于 2023年4月17日 07:53:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76030890.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定