反应来自状态对象的映射项

时间:2019-01-10 02:07:36

标签: javascript reactjs

我有一个React Web应用程序,该应用程序从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;

1 个答案:

答案 0 :(得分:1)

正如您在所附图像中看到的那样,状态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>
    )}
}