簡體   English   中英

React內部的不變違規錯誤

[英]Invariant Violation error inside React

我有這個組件功能

 async FetchCards() {
    axios.get(settings.default.baseUrl + '/api/cards/get_cards').then((data) => {
      var dd = data.data.data;
      //this.setState({cards : d});
      return(
        dd.map(d => {
          <Card style={{flex: 0}}>
          <CardItem>
            <Left>
              <Thumbnail source={{uri: d.img}} />
              <Body>
                <Text>{d.name}</Text>
                <Text note>{d.position}</Text>
              </Body>
            </Left>
            <Right>
                {d.gender == 'male' && <Icon style={{fontWeight : '900' , fontSize:32 , color : 'darkblue'}} name='ios-male'></Icon>}
                {d.gender == 'female' && <Icon style={{fontWeight : '900' , fontSize:32 , color : 'pink'}} name='ios-female'></Icon>}
            </Right>
          </CardItem>
          <CardItem>
            <Body>
              <Text>
                {d.subtitle}
              </Text>
            </Body>
          </CardItem>
        </Card>  
        })
      );
    }).catch((err) => {
      console.log(err);
    });
  }

當我在這里叫它

{this.FetchCards()}

它會引發此錯誤:

不變違規:如果您打算呈現子級集合,則應使用數組來代替對象(作為具有子項{_40,_65,_55,_72}的找到的對象)無效。

看起來您在render方法中直接在JSX中調用this.FetchCards 您可以在componentDidMount獲取數據,並將其設置為組件狀態。

class App extends React.Component {
  state = { cards: [] };

  componentDidMount() {
    axios.get(settings.default.baseUrl + "/api/cards/get_cards").then(data => {
      const cards = data.data.data;
      this.setState({ cards });
    });
  }

  render() {
    const { cards } = this.state;
    return (
      <View>
        {cards.map(c => (
          <Card style={{ flex: 0 }}>
            <CardItem>
              <Left>
                <Thumbnail source={{ uri: c.img }} />
                <Body>
                  <Text>{c.name}</Text>
                  <Text note>{c.position}</Text>
                </Body>
              </Left>
              <Right>
                {c.gender == "male" && (
                  <Icon
                    style={{
                      fontWeight: "900",
                      fontSize: 32,
                      color: "darkblue"
                    }}
                    name="ios-male"
                  />
                )}
                {c.gender == "female" && (
                  <Icon
                    style={{ fontWeight: "900", fontSize: 32, color: "pink" }}
                    name="ios-female"
                  />
                )}
              </Right>
            </CardItem>
            <CardItem>
              <Body>
                <Text>{c.subtitle}</Text>
              </Body>
            </CardItem>
          </Card>
        ))}
      </View>
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM