在React功能组件中使用useEffect时出错

时间:2020-05-14 07:40:20

标签: javascript reactjs frontend react-hooks use-effect

我正在学习使用反应挂钩来管理状态,但是我得到了错误提示 5:3行:在函数“ cockpit”中调用React Hook“ useEffect”,该函数既不是React函数组件也不是自定义的React Hook函数react-hooks / rules-of-hooks

这是我的代码

import React, {useEffect} from "react";
import classes from "./Cockpit.module.css";

const cockpit = (props) => {
  useEffect(() => {
    console.log('Cockpit js useEffect');

  });

  const assiginedClasses = [];
  let btnClass = "";
  if (props.showPersons) {
    btnClass = classes.Red;
  }

  if (props.persons.length <= 2) {
    assiginedClasses.push(classes.red);
  }

  if (props.persons.length <= 1) {
    assiginedClasses.push(classes.bold);
  }
  return (
    <div className={classes.Cockpit}>
      <h1>Hi I'm a React App</h1>
      <p className={assiginedClasses.join(" ")}>This is really Working!</p>
      <button className={btnClass} onClick={props.clicked}>
        Toggle Name
      </button>
    </div>
  );
};

export default cockpit;

5 个答案:

答案 0 :(得分:3)

删除错误解决后,下面的行更改了。 此代码有效。 1. const cockpit =(props)=> { 2.导出默认座舱;

在行下方替换 1. const Cockpit =(props)=> { 2.导出默认的 Cockpit ;

答案 1 :(得分:0)

我认为useEffect钩子更像这样:

useEffect(() => {
  effect
  return () => {
    cleanup
  }
}, [input])

答案 2 :(得分:0)

useEffect(() => {
  console.log('Cockpit js useEffect');
}, []); // []: is used for initial state

useEffect(() => {
   console.log('Cockpit js useEffect');
}, [something]); When {something} is changed call print 'Cockpit js useEffect'


useEffect(() => {
  return () => console.log('unmount'); // return and unmount
}, []);

答案 3 :(得分:0)

功能组件通常以大写字母开头。因此,将名称“ cockpit”更改为“ Cockpit”

答案 4 :(得分:0)

这是来自https://www.npmjs.com/package/eslint-plugin-react-hooks的短毛绒“错误”。

特别是它来自:https://github.com/facebook/react/blob/ddcc69c83b59ef0f895aa5020196e2ae9de36133/packages/eslint-plugin-react-hooks/src/RulesOfHooks.js#L478

isDirectlyInsideComponentOrHook由于组件名称无效而返回false。

        const isDirectlyInsideComponentOrHook = codePathFunctionName
          ? isComponentName(codePathFunctionName) ||
            isHook(codePathFunctionName)
          : isForwardRefCallback(codePathNode) || isMemoCallback(codePathNode);

因此,您会收到此错误:

            } else if (codePathFunctionName) {
              // Custom message if we found an invalid function name.
              const message =
                `React Hook "${context.getSource(hook)}" is called in ` +
                `function "${context.getSource(codePathFunctionName)}" ` +
                'that is neither a React function component nor a custom ' +
                'React Hook function.' +
                ' React component names must start with an uppercase letter.';
              context.report({node: hook, message});
            }

如果您的函数名称不是以大写字母开头,则react将在控制台中显示此“错误”。