gpt4 book ai didi

javascript - 从状态中的对象 react 映射项

转载 作者:行者123 更新时间:2023-11-30 19:54:45 25 4
gpt4 key购买 nike

我有一个 React 网络应用程序,它通过 componentDidMount() 从我的 API 获取一个 JSON 对象。

我可以在 Web 浏览器中查看 React 开发工具中的数据,但我无法将数据映射到 HTML。我在以前的应用程序中这样做过,但它不适用于我当前的对象。

我确信我映射数组的语法存在一个小问题。感谢您的帮助。

image of data object from react tools

import React from "react";
import { BrowserRouter as Router, Link, Route } from 'react-router-dom';

class TeamInformation extends React.Component{
state = {teamNames: []}

constructor(props) {
super(props);
this.state = {
selectedTeam: "none"
};
}

componentDidMount(){
fetch('/users/teamNames')
.then(res => res.json())
.then(teamNames => this.setState({teamNames}));
}

render(){

return (
<div>
<h1>Teams</h1>

{this.state.teamNames.map(teamData =>
<div key={teamData.PK_TeamID}>
<p>{teamData.cityName}</p>
</div>
)}
</div>
)}}

export default TeamInformation;

最佳答案

正如我在您的附加图片中看到的,状态 teamNames 是一个对象而不是数组。您无法映射对象,只需将代码更改为:

constructor(props) {
super(props);
this.state = {
selectedTeam: "none",
teams: []
};
}

componentDidMount(){
fetch('/users/teamNames')
.then(res => res.json())
.then(teamNames => this.setState({teams: teamNames.teamData})); // teamData is an array, not teamNames
}

render(){
...
{this.state.teams.map(team=>
<div key={team.PK_TeamID}>
<p>{team.cityName}</p>
</div>
)}
}

关于javascript - 从状态中的对象 react 映射项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54121028/

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