![](/img/trans.png)
[英]“State” undefined when trying to map fetched json data into React app
[英]map function on React state - state with fetched API data
import Movie from './Movie';
import axios from 'axios';
import yargsParser from 'yargs-parser';
function App() {
const [isLoading, setLoading] = useState(true)
const [movies, setMovie] = useState([])
const getMovies = async () => {
const {data: {data: { movies }}} = await axios.get("https://yts.lt/api/v2/list_movies.json?sort_by=rating");
setMovie([{movies}])
setLoading(false)
}
useEffect(() => {
getMovies();
}, [])
return (
<div className="App">
{isLoading ? "we are loading bunch of movies" : movies.map(movie => console.log(movie))}
</div>
);
}
export default App;
The issue here is that when I check the console, the map function on movies state is returning a single object including all the other objects in it,
而不是單獨返回所有對象。 我想知道為什么? 因此,當我使用 Movie 組件更新返回時,如下所示,
return (
<div className="App">
{isLoading ? "we are loading bunch of movies" : movies.map(movie => (
<Movie key={movie.id} />
))}
</div>
);
這就是 Movie 組件的樣子
import React, { useState } from 'react'
import PropTypes from 'prop-types';
export default function Movie({ id, year, title, summary, poster }){
return <h4>{title}</h4>
}
Movie.propTypes = {
id: PropTypes.number.isRequired,
year: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
summary: PropTypes.string.isRequired,
poster: PropTypes.string.isRequired
}
電影組件沒有收到正確的道具。 我導入道具類型來檢查它,它說
我想知道我應該如何處理電影 state 以獲得正確的電影組件道具?
return (
<div className="App">
{isLoading ? "we are loading bunch of movies" : movies.movies.map(movie => (
<Movie key={movie.id} {...movie}/>
))}
</div>);
或者
setMovie(movies)
綁定數組時仔細檢查,目前似乎鍵是電影,值是數組。 你想直接綁定數組
你應該通過電影作為道具
return (
<div className="App">
{isLoading ? "we are loading bunch of movies" : movies.map(movie => (
<Movie key={movie.id} {...movie} />
))}
</div>
);
您需要將所有道具傳遞給您的組件)
錯誤代碼:
<Movie key={movie.id} {...props}/>
你可以傳遞這個組件需要的任何東西......
你沒有通過 rest 的數據
return (
<div className="App">
{isLoading ? "we are loading bunch of movies" : movies.map(movie => (
<Movie key={movie.id} {...movie}/>
))}
</div>
);
錯誤似乎在對setMovie
的調用中-如果您希望 state 包含電影數組,則不應創建其中包含 object 的數組,而只需將其更改為
setMovie(movies)
在上面的Movie
組件中,結果 object 沒有作為 prop 傳遞給組件。 而是僅使用 map 來渲染組件,數據在數組中出現的次數以及傳遞給組件的唯一鍵。
該代碼可以用作
<Movie key={movie.id} {...movie} />
或者
<Movie key={movie.id} id={movie.id} year={movie.year} title={movie.title} summary={movie.summary} poster={movie.poster} />
const getMovies = async () => {
const {data: {data: { movies }}} = await axios.get("https://yts.lt/api/v2/list_movies.json?sort_by=rating");
**setMovie([ ...movies ])**
setLoading(false)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.