简体   繁体   English

关于使用fetch()和.then()建立反应状态的问题

[英]Question about building react state with fetch() and .then()

I have an issue when I tried to fetch a json file and build the react state. 我尝试获取json文件并建立react状态时遇到问题。

 import React, { Component } from 'react'; class App extends Component { constructor() { super() this.state = { cards: [] } } componentDidMount() { fetch('https://steamcdn-a.akamaihd.net/apps/583950/resource/card_set_1.3E50A21FB5DAFC5864FE5DE99E0EC84E4B3F00DB.json') .then(response => response.json()) .then(cardsets => this.setState({ cards: cardsets.card_set.card_list })) } 

Above is the code I finished. 上面是我完成的代码。 It's working. 工作正常 So at this point I want to let my this.state.cards[i] object have a name 'color', and the value would be based on this.state.cards[i].is_blue or this.state.cards[i].is_red etc (these are just from the json file). 因此,在这一点上,我想让我的this.state.cards[i]对象具有名称“ color”,并且该值将基于this.state.cards[i].is_bluethis.state.cards[i].is_red等(这些仅来自json文件)。

I'm wondering how could I do this. 我想知道我该怎么做。 Please help me I'm very new to react. 请帮助我,我是个新手。

You could map to the wanted format before setting it to the state: 您可以先将其map为所需的格式,然后再将其设置为以下状态:

this.setState({
 cards: cardsets.card_set.card_list.map(({ is_red, is_blue, ...rest }) => ({ 
   color: (is_red && "red") || (is_blue && "blue") || "black",
   ...rest
  })),
});

Then you can access cards[i].color while rendering. 然后,您可以在渲染时访问cards[i].color

Or you just extract the color directly when rendering: 或者您只在渲染时直接提取颜色:

 render() {
  const { cards } = this.state;

  return cards.map(card => {
   const { is_blue, is_red } = card;
   const color = (is_red && "red") || (is_blue && "blue") || "black";

   return <div style={{ color }} >Card</div>;
  });
}

只需更改您的秒数, then使用map

.then(cardsets => this.setState({ cards: cardsets.card_set.card_list.map(card => card.color = card.is_red ? "red" : "blue")}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM