我似乎不明白为什么我的MovieDetailCard组件在电影状态更改时不会重新渲染。我正在传入电影对象。当我更新状态时,日志在useEffect中正确输出,但MovieDetailsCard从未接收到更新的对象。
const MovieDetails = () => {
const [movie, setMovie] = useState({});
const { id } = useParams();
const { poster } = useParams();
useEffect(() => {
const fetchMovie = async () => {
const response = await fetch(
`http://www.randyconnolly.com/funwebdev/3rd/api/movie/movies.php?id=${id}`
);
const data = await response.json();
setMovie({ ...data });
};
fetchMovie();
}, []);
useEffect(() => {
console.log(movie); // this successfully outputs when movie updates
}, [movie]);
return (
<div className="row">
<div className="col s12 m6">
<MovieDetailsCard poster={poster} movie={movie} /> // this does not update
</div>
<div className="col s12 m6">
<CastCrewCard />
</div>
</div>
);
};
下面是MovieDeatailsCard。在useEffect中,console.log(movie(总是返回null。
const MovieDetailsCard = ({ poster, movie }) => {
useEffect(() => {
console.log("in details");
console.log(movie);
}, []);
return (
<div className="card">
<div className="card-content">
<div className="row">
<div className="col s6">
<span className="card-title">Movie Title</span>
</div>
<div className="col s6 favouriteButton">
<FavouriteButton className="waves-effect waves-light btn">
<i className="material-icons">favorite</i>
</FavouriteButton>
</div>
</div>
<div className="row">
<div className="col s12 m6">
<img src={`https://image.tmdb.org/t/p/w342/${poster}.jpg`} alt="" />
</div>
<div className="col s12 m6">
<p>{movie.title}</p>
</div>
</div>
</div>
</div>
);
};
export default MovieDetailsCard;
感谢大家的输入。现在这个问题似乎已经解决了。之前我通过setData(data(设置数据,但当我更改为setData({…data}(时,它起作用了!
默认情况下,效果在每次完成渲染后运行,但只有当某些值发生更改时,才能选择激发效果。
参考:https://reactjs.org/docs/hooks-reference.html#conditionally-发射效果
如果你想运行一个效果并只清理一次(在挂载和unmount(,则可以传递一个空数组([](作为第二个参数。这告诉React,你的效果不取决于道具的任何值或状态,因此它永远不需要重新运行。这不是特别处理的case——它直接遵循依赖项数组作品
尝试更新useEffect依赖性以包括[id]:
useEffect(() => {
const fetchMovie = async () => {
const response = await fetch(
`http://www.randyconnolly.com/funwebdev/3rd/api/movie/movies.php?id=${id}`
);
const data = await response.json();
setMovie({ ...data });
};
fetchMovie();
}, [id]);
您确定要从API接收数据吗?该网站不显示。尝试测试API
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json)
在状态声明(useState(中,最好声明将从API 接收的所有密钥