【发布时间】:2019-07-30 01:40:44
【问题描述】:
我正在尝试返回一个组件,该组件只有在它属于特定类别时才会呈现。我从服务器获取的类别对象有一个 product_id 列表。我将 product_ids 列表传递给组件并检查它是否在列表中,如果在,则返回它。
但是,这样做时,我得到了
FormRow(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
// index.js (Every other function will be in this function as well)
export default function Index({ products, categories }) {
const classes = useStyles();
const theme = useTheme();
return (
<div id="page-container">
...
<div id="products">
{ products && categories && <FormTabComponent/> }
</div>
...
</div>
);
}
所以我正在尝试加载 <FormTabComponent/> 并确保产品和类别都存在。假设这也意味着它也会检查对象是否为空。
所以 FormTabComponent 会渲染下面的组件,看起来渲染得很好。
function FormTabComponent() {
return(
<SwipeableViews>
<TabContainer dir={theme.direction}>
{categories.map((category, key) => (
<Grid key={key} container spacing={1}>
<FormRow productIds={category.product_ids}/>
</Grid>
))}
<Grid container spacing={1}>
<FormRow />
</Grid>
</TabContainer>
</SwipeableViews>
)
}
如下所示的productIds:
[ 'b2c66a6d', '9e303f69', 'cd210ce7', '436ce49c' ]
这是 FormRow,问题出在哪里。
function FormRow({ productIds }) {
products.map((product, key) => {
if (!_.isEmpty(productIds) && productIds.includes(product.id)) {
return (
<React.Fragment>
<Grid key={key} item xs={4}>
<Paper className={classes.paper}>
<Item
id={product.id}
title={product.title}
description={product.description}
currency={product.currency}
price={product.price}
/>
</Paper>
</Grid>
</React.Fragment>
);
}
});
}
如果我 console.log productIds,我会得到预期的结果,没有未定义的结果。
这是我获取数据的方式:
Index.getInitialProps = async ({ req }) => {
const categories = await fetch('http://localhost:3000/api/categories');
const products = await fetch('http://localhost:3000/api/products');
return {
categories: await categories.json(),
products: await products.json()
};
};
所以我不确定我在这里做错了什么。有什么想法吗?
完全错误:
Invariant Violation: FormRow(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
【问题讨论】:
-
您只是在
FormRow组件中的products.map之前缺少一个return。 -
嗨@EmileBergeron,正如第一个答案所建议的那样,我添加了一个else并返回null,但这似乎不起作用。
-
您在
.map回调中添加,而不是我说的,这是您应该返回某些内容的组件,因为function FormRow({ productIds }) {不会隐式返回任何内容。
标签: javascript reactjs next.js