反应渲染 - 对象作为React子对象无效

时间:2017-12-22 09:18:19

标签: reactjs

我试图在渲染中循环我的事件:

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

完整错误是:

对象作为React子项无效(找到:带有键{event,rest_url,total,total_pages}的对象)

有什么想法吗?

3 个答案:

答案 0 :(得分:3)

constletblock scoped,因此该问题属于您的events变量。您可以删除属于if变量&amp;的events语句。将其移至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>
);

答案 1 :(得分:0)

我认为问题是:

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

我猜events是一个常规JavaScript对象?在这种情况下,React不知道如何渲染它。

答案 2 :(得分:0)

您正在第一个if条件中创建一个新的事件变量。

只需删除第一个if语句

中的const即可