简体   繁体   English

react render-对象作为React子对象无效

[英]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}) 对象作为React子对象无效(找到:带有键{events,rest_url,total,total_pages}的对象)

Any ideas? 有任何想法吗?

const s and let s are block scoped , so the issue belongs to your events variable. constlet处于块范围内 ,因此问题属于您的events变量。 You can remove the if statement which belong to events variable & move it to render method, like below: 您可以删除属于events变量的if语句并将其移至render方法,如下所示:

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? 我猜events是常规的JavaScript对象吗? In this case React doesn't know how to render it. 在这种情况下,React不知道如何渲染它。

You are creating a new events variable in first if condition. 您将首先在if条件中创建新的事件变量。

Just delete the const inside first if statement 只需在第一个if语句中删除const

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

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