简体   繁体   中英

react render - objects are not valid as a React child

I am trying to loop through my events in my render:

let {events} = this.props;

    if(events.length > 0) {
       const events = events.map((event) => <Text>{event.author}</Text>);
    }

    if (this.props.hasErrored) {
        return <Text>Sorry! There was an error loading the events</Text>;
    }

    if (this.props.isLoading) {
        return <Text>Loading…</Text>;
    }

    return (
        <View>
          {events}
        </View>
    );

The error in full is:

Objects are not valid as a React child (found: object with keys {events, rest_url, total, total_pages})

Any ideas?

const s and let s are block scoped , so the issue belongs to your events variable. You can remove the if statement which belong to events variable & move it to render method, like below:

const {events} = this.props;

if (this.props.hasErrored) {
  return <Text>Sorry! There was an error loading the events</Text>;
}

if (this.props.isLoading) {
  return <Text>Loading…</Text>;
}

return (
  <View>
    {events && events.length && events.map((event) => <Text>{event.author}</Text>)}
  </View>
);

I think the problem is:

return (
    <View>
      {events}
    </View>
);

I guess events is a regular JavaScript object? In this case React doesn't know how to render it.

You are creating a new events variable in first if condition.

Just delete the const inside first if statement

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