警告 预期在箭头函数结束时返回一个值

时间:2021-02-25 16:55:55

标签: reactjs eslint

我在控制台上收到此警告。但是,在我看来代码是正确的:

{
    report.report.map((item, key) => {
        if (item.status !== "pending_review") {
            return (
                <div key={key}>
                    <Spacing appearance="small" />

                    <Title as="h5" >Data: {formatDate(item.createdAt)}</Title>
                    <Title as="h5" >Realizada por: {item?.reported_by?.users[0]?.name}</Title>

                    <Spacing appearance="x-small" />

                    <Title as="h5" >{item?.description}</Title>

                    <Spacing appearance="medium" />
                </div>
            )
        }
    })
}

1 个答案:

答案 0 :(得分:1)

您在 if 语句后缺少默认返回值:

{
    report.report.map((item, key) => {
        if (item.status !== "pending_review") {
            return (
                <div key={key}>
                    <Spacing appearance="small" />

                    <Title as="h5" >Data: {formatDate(item.createdAt)}</Title>
                    <Title as="h5" >Realizada por: {item?.reported_by?.users[0]?.name}</Title>

                    <Spacing appearance="x-small" />

                    <Title as="h5" >{item?.description}</Title>

                    <Spacing appearance="medium" />
                </div>
            )
        }
        return null; // ?
    })
}

如果您想缩短它并避免使用 if,您可以在映射之前简单地过滤数组:

{
    report.report
      .filter(item => item.status !== "pending_review")
      .map((item, key) => (
         <div key={key}>
           ... content ...
         </div>
      ));
}