[英]Cannot read property 'map' of undefined [React.js]
so when i do my login and i try to redirect to this page it appears me that error it must be something with useEffect i dont know因此,当我登录并尝试重定向到此页面时,我发现该错误一定是 useEffect 我不知道
here is my code这是我的代码
useEffect(() => {
let canUpdate = true;
getVets().then((result) => canUpdate && setVets(result));
return function cleanup() {
canUpdate = false;
};
}, []);
const getVets = async () => {
const url = 'http://localhost:8080/all/vet';
const response = await fetch(url);
const data = await response.json();
setVets(data);
};
// const { appointmentType, animalID, room, hora, notes } = this.state;
return (
<React.Fragment>
<div class='title'>
<h5>2 médicos vetenários disponíveis</h5>
</div>
<div>
{vets.map((data) => (
<ObterMedicos
key={data.name}
name={data.name}
specialty={data.specialty}
/>
))}
</div>
</React.Fragment>
);
} }
vets might not have data on the first render and when the code tries to execute map operation on it, it gets undefined.map
, which is not allowed. vets 在第一次渲染时可能没有数据,当代码尝试对其执行 map 操作时,它会得到
undefined.map
,这是不允许的。
You can either set vets to empty array at the time of defining the state您可以在定义 state 时将 vets 设置为空数组
const [vets,setVets] = useState([]);
or just check on vets using Optional chaning (?) before using the map function:或者在使用 map function 之前使用可选 chaning (?) 检查兽医:
{vets?.map((data) => (
<ObterMedicos
key={data.name}
name={data.name}
specialty={data.specialty}
/>
))}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.