繁体   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