简体   繁体   中英

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.

 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).

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:

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.

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")}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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