将返回的 api 数据设置为反应状态

Posted

技术标签:

【中文标题】将返回的 api 数据设置为反应状态【英文标题】:Setting returned api data as react state 【发布时间】:2019-12-24 05:48:41 【问题描述】:

我试图在下面设置这个反应组件的状态。变量 rankAndTeam 包含下面的“prints=>”数据。我希望将“华盛顿首都”设置为 this.state.teamRank["0"]..."New York Islander" 设置为 this.state.teamRank["1"] 等...

    this.state = 
      teamRank: 
        0: "",
        1: "",
        2: "",
        3: "",
        4: "",
        5: "",
        6: "",
        7: "",
      
    
  

  async componentDidMount() 
    const url2 = 'https://statsapi.web.nhl.com/api/v1/standings';
    const response2 = await fetch(url2);
    const data2 = await response2.json();
    data2.records.map((element) => 
      element.teamRecords.map((element2, index) => 
        const teamNames = element2.team.name;
        const rankAndTeam = teamNames + index;
        console.log(rankAndTeam);
      );
    

打印

Main.js:80Washington Capitals0
Main.js:80 New York Islanders1
Main.js:80 Pittsburgh Penguins2
Main.js:80 Carolina Hurricanes3
Main.js:80 Columbus Blue Jackets4
Main.js:80 Philadelphia Flyers5
Main.js:80 New York Rangers6
Main.js:80 New Jersey Devils7

反应组件:

Want to put this.state.teamRank.['0'] where Name0 is...
Want to put this.state.teamRank.['1'] where Name1 is etc... 
  <tr>
    <th></th>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Username</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>1</td>
    <td>Name0</td>
    <td>Otto</td>
    <td>@mdo</td>
  </tr>
  <tr>
    <td>2</td>
    <td>Name1</td>
    <td>Thornton</td>
    <td>@fat</td>
  </tr>
  <tr>
    <td>3</td>
    <td>Name2</td>
    <td>Thornton</td>
    <td>@fat</td>
  </tr>

【问题讨论】:

【参考方案1】:

你问题的第二部分是简单的 JSX:

                               <tr>
                                    <th></th>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Username</th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr>
                                    <td>1</td>
                                    <td>this.state.teamRank[0]</td>
                                    <td>Otto</td>
                                    <td>@mdo</td>
                                </tr>
                                <tr>
                                    <td>2</td>
                                    <td>this.state.teamRank[1]</td>
                                    <td>Thornton</td>
                                    <td>@fat</td>
                                </tr><tr>
                                    <td>3</td>
                                    <td>this.state.teamRank[2]</td>
                                    <td>Thornton</td>
                                    <td>@fat</td>
                                </tr>

编辑:在*** JSX 旁边试试这个:

     this.state = 
        teamRank:[
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            ""
        ]
    

async componentDidMount() 
const url2 = ('https://statsapi.web.nhl.com/api/v1/standings');
    const response2 = await (fetch(url2));
    const data2 = await response2.json();
    data2.records.map((element)=>
            element.teamRecords.map((element2,index) => 
                const teamNames = element2.team.name;
                teamRank = this.state.teamRank
                teamRank[index] = name
                this.setState(teamRank: teamRank);
                const rankAndTeam = teamNames + index;
                console.log(rankAndTeam);
   );

【讨论】:

不正确。 this.state.teamRank[1] 登录未定义对象【参考方案2】:

您需要创建一个新对象作为您的新状态,然后将状态设置为这个新对象,如下所示 (由于您没有创建新数组,因此可以使用 forEach 代替 map)

let newState = 
element.teamRecords.forEach((element2,index) => 
          const teamNames = element2.team.name;
          const rankAndTeam = teamNames + index;
          console.log(rankAndTeam);
          // this will add a key of index (0,1,2,3...) with the team name as value 
          newState[index] = teamNames
   );
this.setState( teamRank: newState)

在您的组件中,您可以遍历对象的键并呈现信息

这里你正在创建一个 tr 数组,React 会处理并正确渲染它

  // rank will be (0,1,2,3...)
 Object.keys(this.state.teamRank).map(rank => (
    <tr>
       <td>rank + 1</td>
       <td>this.state.teamRank[rank]</td>
       <td>Otto</td>
       <td>@mdo</td>
    </tr>
  ))

【讨论】:

【参考方案3】:

您的 data2.records 数组包含 4 个对象。在每个对象中,您都有 teamRecords 数组,其中自身包含 8 个对象。

考虑到您只想显示前 8 条记录。你有两个选择。

你需要有数组而不是对象,

this.state = 
    teamRank: []

选项 1

创建一个数组,将每个名称推送到该数组中,最后将该数组存储在状态中。

let teamRank = [];
data2.records.map((element,ind)=>
  element.teamRecords.map((element2,index) => 
    const teamNames = element2.team.name;
    const rankAndTeam = teamNames + index;
    console.log(rankAndTeam);
    teamRank.push(teamNames)
  );
)

this.setState(teamRank, ()=>console.log(this.state.teamRank))

你可以像这样打印名字,

<tbody>
  <tr>
    <td>1</td>
    <td> this.state.teamRank && this.state.teamRank[0]</td>
    <td>Otto</td>
    <td>@mdo</td>
  </tr>
  <tr>
    <td>2</td>
    <td> this.state.teamRank && this.state.teamRank[1]</td>
    <td>Thornton</td>
    <td>@fat</td>
  </tr><tr>
    <td>3</td>
    <td> this.state.teamRank && this.state.teamRank[2]</td>
    <td>Thornton</td>
    <td>@fat</td>
  </tr>
</tbody>

Demo


选项 2

您可以通过迭代 data2.records 来创建一个数组数组

let teamRank = data2.records.map((element,ind)=>
  return element.teamRecords.map((element2,index) =>   //Notice the return
    const teamNames = element2.team.name;
    const rankAndTeam = teamNames + index;
    console.log(rankAndTeam);
    return teamNames;  //Notice the return
  ); 
)

this.setState(teamRank, ()=>console.log(this.state.teamRank))

你可以打印名字,

<tbody>
  <tr>
    <td>1</td>
    <td> this.state.teamRank[0] && this.state.teamRank[0][0]</td>
    <td>Otto</td>
    <td>@mdo</td>
  </tr>
  <tr>
    <td>2</td>
    <td> this.state.teamRank[0] && this.state.teamRank[0][1]</td>
    <td>Thornton</td>
    <td>@fat</td>
  </tr><tr>
    <td>3</td>
    <td> this.state.teamRank[0] && this.state.teamRank[0][2]</td>
    <td>Thornton</td>
    <td>@fat</td>
  </tr>
</tbody>

Demo

【讨论】:

以上是关于将返回的 api 数据设置为反应状态的主要内容,如果未能解决你的问题,请参考以下文章

反应 SPA。用于处理登录状态的全局状态存储 API?

如何使用 api 的数据初始化状态

反应原生返回 null 状态

如何使用返回的 json 对象中的特定项目设置反应组件的状态?

如何将 json 数据返回到反应状态?

如何设计 API 接口,实现统一格式返回?