[英]React - nothing was returned from render
我有一個需要渲染一個鏈接的組件,或者如果該項目是一個數組,則渲染該數組中的每個項目,並用'/'分隔。
我收到以下錯誤消息:我的渲染組件未返回任何內容。 我認為這是因為我使用的是if else語句,但我不確定。
class Item extends React.Component {
constructor(props) {
super(props)
this.renderArray = this.renderArray.bind(this)
}
renderArray (item) {
const items = item
items.forEach((item, key) => {
return (
<a href={item.link} title={item.text} /> + '/'
)
})
}
render () {
const { item } = this.props
const { link, text, classes } = item
if (!link && text) {
return (
<span>
<br />
<strong dangerouslySetInnerHTML={{ __html: text }} />
</span>
)
}
const className = classNames(
classes
)
if (Array.isArray(item)) return this.renderArray(item)
return (
<a href={link} className={className} title={text} dangerouslySetInnerHTML={{ __html: text }} />
)
}
}
您的renderArray()方法當前不返回任何內容。 嘗試將其更新為以下內容:
renderArray (items) {
return items.map((item, key) => {
return (
<a href={item.link} title={item.text} /> + '/'
)
})
}
由於您使用forEach
進行循環,因此在這種情況下不會返回任何內容。
您可以使用map
功能進行循環。
renderArray (items) {
return items.map((item, key) => {
return (
<a href={item.link} title={item.text} /> + '/'
)
})
}
或者您可以使用
renderArray (item) {
const items = item;
let contentToRender = [];
items.forEach((item, key) => {
contentToRender.push(
<a href={item.link} title={item.text} /> + '/'
)
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.