【问题标题】:Why am I getting Warning: Functions are not valid as a React child?为什么我收到警告:函数作为 React 子级无效?
【发布时间】:2018-08-01 05:41:40
【问题描述】:

当我尝试调用返回 map 方法结果的方法时,我收到以下错误 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render 但我不知道为什么。这是我的代码:

renderAlbums() {
        return this.state.albums.map(album => <Text>{ album.title }</Text>);
    }

    render() {
        return (
            <View>
                { this.renderAlbums }
            </View>
        );
    }

但是我上面的代码我看不出问题出在哪里。但是,当我尝试在我的 render() 方法中创建一个变量并传递我的 map() 方法时,一切正常:

render() {
  const c=this.state.albums.map(album => <Text>{ album.title }</Text>);
    return (
        <View>
            { c }
        </View>
    );
}

我想了解它为什么不起作用。当我在这里调用渲染renderAlbums() 方法时&lt;View&gt;{ this.renderAlbums }&lt;/View&gt;

而且对我来说更奇怪的是,当我尝试像这样用括号调用 renderAlbums() 时,它可以工作。

【问题讨论】:

  • 您没有执行该功能,您只是提供参考。 this.renderAlbums() 将执行它
  • 也谢谢你,你帮助我更好地理解了

标签: reactjs react-native


【解决方案1】:

警告:函数作为 React 子级无效。如果您返回 Component 而不是从渲染中返回,则可能会发生这种情况

基本上,React 期望 React Elements 呈现它。

在当前脚本中,this.renderAlbums 是一个函数引用,它不返回任何React Element。函数本身不是反应元素。所以,React 无法渲染this.renderAlbums

<View>
   { this.renderAlbums }
</View>

正确方法:

<View>
   { this.renderAlbums() } //it will return react element which can be rendered.
</View>

【讨论】:

  • 我在使用 React Native 时也遇到了同样的错误,我正在调用一个函数,该函数返回另一个函数,该函数返回一个组件。例如,在最近的 Udacity 项目中,我本应调用 {getMetricMetaInfo('bike').getIcon()} 时调用了 {getMetricMetaInfo('bike').getIcon} 注意第二个函数上的第二组括号执行函数。
【解决方案2】:

我想我应该分享我对这个错误的经验,我的代码:

const PageMakeup = loading ? ThemLoading : (
<div>....</div>
);

这里的问题是ThemLoading被包含在其他文件中,应该是&lt;ThemLoading /&gt;; 并且这个错误被清除了!

关于你的错误:回调函数和返回函数是不同的,你的情况是返回函数this.renderAlbums();,而不是this.renderAlbums

美好的一天!

【讨论】:

    【解决方案3】:

    this.renderAlbums 指的是实际的函数本身,而this.renderAlbums() 实际执行的是函数,因此代表了函数的返回值。

    【讨论】:

      【解决方案4】:

      返回整个函数,而不是指向函数

       return (
                  <View>
                      { this.renderAlbums() }
                  </View>
              );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-16
        • 2018-12-15
        • 2018-11-05
        • 2021-01-03
        • 2020-03-09
        • 1970-01-01
        • 2019-06-15
        • 2018-10-16
        相关资源
        最近更新 更多