【发布时间】:2021-10-10 16:22:13
【问题描述】:
我正在尝试将数据从 JSON 文件(动物列表)导入到 React 组件中。
我收到此错误:
TypeError:无法读取未定义的属性“地图”。
我不知道为什么,因为它是在我的 Animal 组件中定义的。
这是我的 json 文件:
[
{
"animalName":"lion",
"animalPic": "images/lion",
"animalSpecies": "Panthera leo",
"animalEnclsoure": " North East side of the Zoo. ",
"animalDescription":" Our lions are our most popular animals and it's easy to see why. They have golden coats, and the males have manes. They also have powerful legs, teeth and jaws which were used to hunt prey in the wild."
},
{
"animalName":"cheetah",
"animalPic": "images/cheetah",
"animalSpecies": "A. jubatus",
"animalEnclsoure": " North East side of the Zoo. Close to the lions ",
"animalDescription":" Our Cheetahs are native from Africa. They are the fastest land animal and can reach speeds of 80mph. They are known for their spotted coats and black snouts."
},
{
"animalName":"Zebra",
"animalPic": "images/zebra",
"animalSpecies": "Equus grevyi,E. quagga,E. zebra",
"animalEnclsoure": " South West side of the Zoo. Close to the entrance",
"animalDescription":" Zebras are well known because of their stripes. They are native to Africa. "
},
{
"animalName":"Crocodile",
"animalPic": "images/crocodile",
"animalSpecies": "Crocodylidae",
"animalEnclsoure": " North West side of the Zoo. Opposite the Lions.",
"animalDescription":" Crocodiles native from the tropics in Africa. They are moree closley rleated to birds and dinosaurs than other reptiles. They hunt mainly at night due to their nocturnal vision. "
}
]
这是我的动物部分:
import React from 'react';
import "../animal.css";
const animal = (props) => {
return (
<div className="Animal">
<h2>{props.animalName}</h2>
<img className="animalPic" src={props.animalPic} alt={props.aniamlName} />
<p>Species{props.animalSpecies}</p>
<p>Enclosure Location{props.animalEnclosure}</p>
<p>Description:{props.animalDescription}</p>
</div>
)
};
export default animal;
这是我的 Zoo-Animal 组件
import React from 'react';
import Animal from './components/Animal';
const zoo = (props) => {
return (
<div className="Animal-output">
{props.animals.map((animal, i) => (
<Animal key={i} {...animal} />
))}
</div>
)
};
export default zoo;
这是我的动物页面:
import React, {useState, useEffect} from 'react'
import Header from './components/Header';
import "./App.css";
import Animal from'./components/Animal';
import Zoo_Animals from './Zoo_Animals.js'
function Animals(props) {
const [animals, setAnimals] = useState([]);
useEffect(() => {
fetch("./json/animal-list.json").then(function(jresponse) {
if(jresponse.ok) {
jresponse.json().then(function(json) {
setAnimals(json);
});
} else {
console.log('error' + jresponse.status + ": " + jresponse.text);
}
});
});
return(
<div>
<h1>Animals</h1>
<Zoo_Animals/>
</div>
)
}
export default Animals;
【问题讨论】:
标签: javascript json reactjs jsx