gpt4 book ai didi

javascript - 带有钩子(Hook)的功能组件导致 "cannot read property map of undefined"

转载 作者:行者123 更新时间:2023-12-04 01:35:37 25 4
gpt4 key购买 nike

我做了一个经典组件和一个功能组件,它们应该做同样的事情。他们都从我的 API 中提取数据,然后将其映射到 Div。但是,这不适用于功能组件,我宁愿使用带钩子(Hook)的功能组件。

我也尝试过使用“UseLayoutEffect” Hook 。我知道会发生这种情况,因为第一次加载组件时,Games 是未定义的,它会尝试映射未定义的,但经过一小段延迟后,API 调用完成,Games 现在是一个对象数组。但是,它已经尝试映射未定义。我有一个条件“游戏”,如果它未定义,它应该阻止它被映射,但由于某种原因它通过了这个条件。

经典组件(工作):

class Player extends React.Component {
constructor(props) {
super(props);
this.state = {
games: [],
players: {},
};
}

componentDidMount() {
this.fetchData()
}

async fetchData() {
const id = window.location.pathname.split('/')[2];
const games = await axios(`/api/players/${id}`);
this.setState({ games: games.data });
}

render() {
return(
<div>
{this.state.games.map((game, i) => (
<div className="historyId" key={i}>{game.match_id}</div>
))}
</div>
);
}

}

功能组件(不工作):未捕获的类型错误:无法读取未定义的属性“映射” 在播放器 (bundle.js:1422)

const Player = (props) => {
let { id } = useParams();
const [games, setGames] = useState({});

useEffect(() => {
async function fetchData() {
const response = await axios(`/api/players/${id}`);
setGames(response);
}
fetchData();
}, []);
return (
<div className="historyContainer">
<h1>Match history here...</h1>
{games && games.data.map((game, i) => <div>{game.match_id}</div>)}
</div>
);
}

最佳答案

您正在检查 games 是否存在,但它有一个默认值(空对象),因此它将始终存在。您不会检查 games.data 是否存在 - 在您的 HTTP 请求完成之前它不会。

试试这个:

{games.data && games.data.map((game, i) => <div>{game.match_id}</div>)}

关于javascript - 带有钩子(Hook)的功能组件导致 "cannot read property map of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59709107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com