在功能组件中使用“ useEffect”时出现错误

时间:2020-07-26 09:10:30

标签: javascript reactjs react-native react-router

我正在尝试使用UseEffect react hook,但出现错误: React Hook的“ useEffect”在函数“ cockpit”中被调用,该函数既不是React函数的组件,也不是自定义的React Hook函数。

import React, { useEffect } from "react";
import styled from "styled-components";
import "./cockpit.css";

// it is a css code
const StyledButton = styled.button`
  background-color: ${props => (props.alt ? "red" : "green")};
  border: 1px solid blue;
  padding: 8px;

  &:hover {
    background-color: ${props => (props.alt ? "salmon" : "lightgreen")};
    color: black;
  }
`;

const cockpit = props => {
  useEffect(() => {
    console.log("in useEffect");
  });

  const classess = [];
  if (props.persons.length <= 2) {
    classess.push("red");
  }
  if (props.persons.length <= 1) {
    classess.push("bold");
  }

  return (
    <div>
      <h1>{props.title}</h1>
      <p className={classess.join(" ")}>Hi, I am React App</p>
      <StyledButton
        key="B1"
        alt={props.showPerson}
        onClick={props.switchNameHandler}
      >
        Switch Name
      </StyledButton>
      <StyledButton
        alt={props.showPerson}
        key="B2"
        onClick={props.togglePersonHandler}
      >
        Toggle Name
      </StyledButton>
    </div>
  );
};

export default cockpit;

任何人都可以帮助我了解我为什么出错了。

package.json中的依赖项

"dependencies": {
    "@react-native-community/cli": "^4.10.1",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "radium": "^0.26.0",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-native": "^0.63.2",
    "react-native-version-update": "^0.2.7",
    "react-scripts": "3.4.1",
    "styled-components": "^5.1.1"
}

2 个答案:

答案 0 :(得分:1)

反应是因为所有定制组件need to be capitalized都无法将cockpit识别为组件。

要解决此问题,只需将组件Cockpit的名称大写即可。

答案 1 :(得分:0)

反应挂钩只能在功能组件的顶部或自定义挂钩中使用。您不能在函数内部使用钩子。选中hook rules