当我试图调用一个返回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>
);
}
我想知道为什么它不起作用。当我在这里调用renderrenderAlbums()
方法时,<View>{ this.renderAlbums }</View>
。
对我来说更奇怪的是,当我试着用括号把renderAlbums()
称为<View>{ this.renderAlbums() }</View>
时,它就起作用了。
警告:函数作为React子级无效。如果您返回组件而不是从渲染返回组件,则可能会发生这种情况
基本上,React期望React Elements
渲染它。
在当前脚本中,this.renderAlbums
是一个不返回任何React Element
的函数引用。函数本身不包含react元素。因此,React无法呈现this.renderAlbums
。
<View>
{ this.renderAlbums }
</View>
正确方式:
<View>
{ this.renderAlbums() } //it will return react element which can be rendered.
</View>
this.renderAlbums
指的是实际函数本身,而this.renderAlbums()
实际执行函数,因此表示函数的返回值。
我想我应该分享我关于这个错误的经验,我的代码:
const PageMakeup = loading ? ThemLoading : (
<div>....</div>
);
这里的问题是ThemLoading包含在其他文件中,应该是<ThemLoading />
;这个错误被清除了!
关于您的错误:回调函数和返回函数是不同的,在您的情况下是返回函数this.renderAlbums();
,而不是this.renderAlbums
;
你好!
不指向函数,而是返回整个函数
return (
<View>
{ this.renderAlbums() }
</View>
);