TypeError:无法读取未定义的属性“map”,但状态已存储
2021-03-31
77
我试图从数据库获取特定团队数据并将其存储在状态中。但是,当我将数组映射到该数据中时,它会返回错误。当我在控制台记录我的状态时,它会返回以下数据
createdAt: "2021-03-19T13:36:22.868Z"
gameEvent: "basketball"
players: Array(5)
0: {_id: "605ea59c5cdf492b48987107", name: "Jerry Ale", jerseyNumber: "12"}
1: {_id: "605ea59c5cdf492b48987108", name: "Judel Agur", jerseyNumber: "14"}
2: {_id: "605ea59c5cdf492b48987109", name: "qwe", jerseyNumber: "12"}
3: {_id: "605ea59c5cdf492b4898710a", name: "qwe", jerseyNumber: "12"}
4: {_id: "605ea59c5cdf492b4898710b", name: "qwe", jerseyNumber: "12"}
length: 5
__proto__: Array(0)
teamName: "Balilihan"
updatedAt: "2021-03-27T03:25:16.148Z"
__v: 0
_id: "6054a8d63fec5c24389624ac"
我有一个 useEffect 来收集这些数据;
useEffect(() => {
const getTeam = async () => {
try {
const { data } = await fetchContext.authAxios.get('get-all-teams');
setIsLoaded(true);
if (isLoaded === true) {
setCurrentTeam(data.find((team) => team._id === row._id));
}
} catch (err) {
console.log(err);
}
};
getTeam();
}, [fetchContext, row, isLoaded]);
并且我将
players
数组映射到一个新变量中,因为我想要一个受控的表单输入,因为我正在更新数据。顺便说一下,我正在使用 Formik
let playersOfTeam = currentTeam.players.map((player, index) => [
{
name: player.name,
jerseyNumber: player.jerseyNumber,
},
]);
但是,当我仅获得 teamName 等特定值时,它会返回 teamName,而当我在控制台记录 currentTeam.players 时,它会返回我期望获得的内容。我很困惑为什么我会收到这种错误
1个回答
首次安装组件时,您的数据未定义。这是因为
useEffect
在渲染之后运行。
因此,添加空检查是解决方案。我个人更喜欢可选链。只需更改为:
let playersOfTeam = currentTeam?.players?.map((player, index) => [
{
name: player.name,
jerseyNumber: player.jerseyNumber,
},
]);
Sinan Yaman
2021-03-31