反应 useEffect 方法上的箭头体式错误

arrow-body-style error on react useEffect method

这是我使用 React 的代码 useEffect

    const [naked, setNaked] = useState(false);

    useEffect(() => {
        return () => setNaked(true);
    }, [props.onWatch]);

出于某种原因,我遇到以下 eslint 错误:

 Unexpected block statement surrounding arrow body  arrow-body-style

即使用括号括起来仍然有同样的问题:

    const [naked, setNaked] = useState(false);

    useEffect(() => {
        return () => {
          setNaked(true);
        }
    }, [props.onWatch]);

谁有解决这个 eslint 错误的好主意? 请 ?谢谢

错误结果取决于您在 .eslintrc 文件中配置 eslint 的方式

If the config is "arrow-body-style": ["error", "always"]

这意味着你需要明确的return和括号,在这种情况下解决方案是

const [naked, setNaked] = useState(false);

useEffect(() => {
    return () => {
      setNaked(true);
    }
}, [props.onWatch]);

If the config is "arrow-body-style": ["error", "never"]

那么你不必使用{},在这种情况下你的解决方案是

const [naked, setNaked] = useState(false);

useEffect(() => () => setNaked(true), [props.onWatch]);

If the config is "arrow-body-style": ["error", "as-needed"]

在这种情况下,您也不需要 return 大括号,您的解决方案是

const [naked, setNaked] = useState(false);

useEffect(() => () => {
      setNaked(true);
}, [props.onWatch]);

请访问following link了解更多关于此规则的信息

您可以在官方 ESLint 文档中找到正确和错误代码的示例。有关此特殊错误的更多信息,请参见此处:arrow-body-style。 简而言之:

Arrow functions have two syntactic forms for their function bodies. They may be defined with a block body (denoted by curly braces) () => { ... } or with a single expression () => ..., whose value is implicitly returned.

您的 return 有一个额外的箭头功能。 要使您的代码符合 ESLint,请使用以下内容:

const [naked, setNaked] = useState(false);

useEffect(() => () => setNaked(true), [props.onWatch]);

我还建议您在您选择的 IDE 中设置 ESLint,这样您就可以突出显示错误或使用简短命令修复文件。