我已经从端点获取了一些数据并将其存储在状态中。当我尝试在控制台中查看结果时,它工作正常。但是,当我尝试在组件中使用它时,它将引发错误,表明密钥未定义。这是我的代码, heroImage 未定义,请帮助
const Home = () => {
const [state, setState] = useState({ movies: [] });
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const fetchMovies = async endpoint => {
setIsError(false);
setIsLoading(false);
const params = new URLSearchParams(endpoint);
if (!params.get("page")) {
setState(prev => ({
...prev,
movies: [],
searchItem: params.get("query")
}));
}
try {
const result = await fetch(endpoint)).json();
setState(prev => ({
...prev,
movies: [...prev.movies, result.results],
heroImage: prev.heroImage || result.results[0],
currentPage: result.page,
totalPage: result.total_pages
}));
} catch (error) {
setIsError(true);
}
setIsLoading(false);
};
useEffect(() => {
fetchMovies(`${API_URL}movie/popular?api_key=${API_KEY}&page=1`);
}, []);
return (
<>
<div className="rmdb-home">
<div>
<HeroImage
image={`${IMAGE_BASE_URL}${BACKDROP_SIZE}${state.heroImage.backdrop_path}`}
/>
<SearchBar />
</div>
</div>
</>
);
};
答案 0 :(得分:0)
因为您的组件在首次渲染时尝试访问heroImage
,但未定义
因此,您需要heroImage
的初始状态
喜欢
const [state,setState]=useState({movies:[], heroImage: {}})