如何解决在ReactJS中访问嵌套的JSON数据
我尝试从端点获取数据并获取错误:对象作为React子代无效。如果要渲染子代的集合,请改用数组。
import React,{ useState,useEffect } from "react";
import { useHistory } from "react-router-dom";
import axios from "axios";
import PropTypes from "prop-types";
import Movie from "./Movie/Movie";
const Movies= () => {
const history = useHistory();
const [renderedMovies,setRenderedMovies] = useState([]);
useEffect(() => {
const requestOptions = {
method: "GET",headers: {
"Content-Type": "application/json",Authorization:
JSON.parse(localStorage.getItem("tokenType")) +
" " +
JSON.parse(localStorage.getItem("accesstoken")),},};
axios
.get("/movies",requestOptions)
.then((response) => {
setRenderedMovies(response.data);
})
.catch((err) => alert(err));
},[]);
return (
{ renderedMovies && (
<ul className="movies_list">
{renderedMovies.map((movie) => (
<Movie
key={movie.movieName}
startTime={movie.startTime}
finishTime={movie.finishTime}
duration={movie.duration}
author={movie.author}
movieDescription={movie.movieDescription}
movieCollection={movie.movieCollection}
clicked={() => history.push(`/movies/${movie.movieName}`)}
/>
))}
</ul>
)}
);
};
Sessions.propTypes = {
startTime: PropTypes.string.isrequired,finishTime: PropTypes.string.isrequired,duration: PropTypes.string.isrequired,author: PropTypes.string.isrequired,movieDescription: PropTypes.string.isrequired,movieCollection: PropTypes.string.isrequired
};
export default Movies;
Movie.js
import React from "react";
import "./Movie.css";
const Movie= (props) => {
return (
<li>
<div onClick={props.clicked}>
<div className="movie_details">
<span>{props.movieName}</span>
<span>{props.startTime}</span>
<span>{props.finishTime}</span>
<span>{props.duration}</span>
<span>{props.author}</span>
<span>{props.movieDescription}</span>
<span>{props.movieCollection}</span>
<span>{props.screenshots}</span>
</div>
</div>
</li>
);
};
export default Movie;
这是邮递员那个端点的样子:
http://localhost:8000/movies
[
{
"movieName": "Titanic","startTime": "2020-09-11T07:20:00.000+00:00","finishTime": "2020-09-11T09:00:00.000+00:00","duration": 100,"author":
{
"Author1","Author2"
},"movieDescription": "description","movieCollection": [
{
"timeMade": "2020-08-29T12:58:11.000+00:00","category": "new"
},{
"timeMade": "2020-07-29T12:58:11.000+00:00","category": "new"
}],"id": 1
},{
"movieName": "Harry Potter","id": 2
}
]
我尝试从端点获取数据并获取错误:对象作为React子代无效。如果要渲染子代的集合,请改用数组。
解决方法
movieCollection
是一个对象数组。因此,请像这样使用:CodeSandbox
<span>
{props.movieCollection.map(
({ timeMade,category }) => timeMade + " " + category
)}
</span>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。