如何将预期的 linter 修复为 return 反应功能组件末尾的值?

How to fix linter expected to return a value at the end of react function component?

我创建了一个函数组件来呈现错误消息,但它有一个 linter 警告“Expected to return a value at the end of function 'renderErrorMessage' consistent-return

function renderError() {
    if (errors.file) {
      return (
        <Grid item>
          <Grid container direction="column">
            <Grid item>
              <Text size="14px" height="1.43" isError>
                Error Data :
              </Text>
            </Grid>
            {errors.file.map((message) => (
              <Grid item key={message}>
                <Text size="12px" isError>
                  {message}
                </Text>
              </Grid>
            ))}
          </Grid>
        </Grid>
      );
    }
}

如果 errors.file 条件为假,您的函数将不会 return 任何值,这就是您收到警告的原因。您可以像这样重构您的组件:

function renderError() {
  if (!errors || !errors.file) {
    return null;
  }

  return (
    <Grid item>
      <Grid container direction="column">
        <Grid item>
          <Text size="14px" height="1.43" isError>
            Error Data :
          </Text>
          </Grid>
          {errors.file.map((message) => (
            <Grid item key={message}>
              <Text size="12px" isError>
                {message}
              </Text>
            </Grid>
          ))}
        </Grid>
      </Grid>
    );
}