在我的反应函数中.log我似乎无法将属性控制台

  • 本文关键字:属性 控制台 log 函数 reactjs
  • 更新时间 :
  • 英文 :


我的控制台允许我接收数组数据,并向我显示它接收了一个对象,但我无法访问对象的属性。我需要这些信息,以便我可以路由此信息并创建电影div。我对 React 很陌生,所以有人可以向我解释一下我如何能够做到这一点,请......当我控制台.log(movieID(时,它呈现了两次,但第一次它是一个未定义的变量。

import axios from 'axios';
export const Movie = (props) => {
const [movie, setMovie] = useState([]);
useEffect(() => {
const snatchMovies = () => {
const id = props.match.params.id;
// change ^^^ that line and grab the id from the URL
// You will NEED to add a dependency array to this effect hook
axios
.get(`http://localhost:5000/api/movies/`)
.then(response => {
setMovie(response.data);
})
.catch(error => {
console.error(error);
});
}
snatchMovies()
},[]);

// Uncomment this only when you have moved on to the stretch goals
// const saveMovie = () => {
//   const addToSavedList = props.addToSavedList;
//   addToSavedList(movie)
// }
if (!movie) {
return <div>Loading movie information...</div>;
}
//const { title, director, metascore, stars } = movie;
const movieId = movie.find(i => props.match.params.id === `${i.id}`);
console.log(movieId.title)
return "hi"
/*
return (
<div className="save-wrapper">
<div className="movie-card">
<h2>{movieId.title}</h2>
<div className="movie-director">
Director: <em>{movieId.director}</em>
</div>
<div className="movie-metascore">
Metascore: <strong>{movieId.metascore}</strong>
</div>
<h3>Actors</h3>
{movieId.stars.map(star => (
<div key={star} className="movie-star">
{star}
</div>
))}
</div>
<div className="save-button">Save</div>
</div>
);
*/
}
export default Movie;

我已经在代码中添加了注释和可能的解决方案,希望对您有所帮助。如果您有任何问题,请发表评论。

import React, { useState, useEffect } from 'react';
import axios from 'axios';
//you can't export default props=>jsx because the linter
//  may complain about anonymous/unnamed function
//  but you can export default like this:
export default function Movie(props) {
//renamed to movies because you are getting multiple movies
const [movies, setMovies] = useState([]);
//made this simpler and removed id, you never use it
useEffect(() => {
axios
.get(`http://localhost:5000/api/movies/`)
.then(response => {
setMovies(response.data);
})
.catch(error => {
console.error(error);
});
//you don't need to get movies again when id changes
//  because you already have all the movies
}, []);
//changed movieId to movie since that is what you
//  want to get 
const movie = movies.find(
i => props.match.params.id === `${i.id}`
);
//now it makes sence to check if movie (single) is falsy
// before movie was [] and if([]) is always truthy
if (!movie) {
return <div>Loading movie information...</div>;
}
console.log(movie.title);
return 'hi';
}

最好让效果按id获取特定电影,如果您有数百万部电影,则不想获取所有电影,然后过滤掉所需的电影。

您正在组合表示组件和容器组件,如果您有很多组件,这将在以后混淆。最好将Movie重命名为MovieContainer,并使其仅使用钩子,然后返回将创建jsx的Movie。容器不应该导入 React,因为它不应该自己生成 jsx,而应该只调用表示组件。

此处为容器示例,此处为表示组件示例

相关内容

最新更新