【问题标题】:Error: Invalid hook call how can i solve it?错误:无效的挂钩调用我该如何解决?
【发布时间】:2021-11-14 23:00:05
【问题描述】:

这是我收到的错误

错误:无效的挂钩调用。钩子只能在体内调用 的一个功能组件。这可能发生在以下情况之一 原因:

  1. 您可能有不匹配的 React 版本和渲染器(例如 React DOM)
  2. 您可能违反了 Hooks 规则
  3. 您可能在同一个应用程序中拥有多个 React 副本 有关如何调试的提示,请参阅 https://reactjs.org/link/invalid-hook-call 并解决此问题。

这是我的代码:

const HandleAdd = () => {
  const [reRender, setRerender] = useState(false);
  Swal.fire({
    title: 'Add Department',
    text: "Input department name below.",
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Save',
    html: generateInputForms({
      strname: '',
      intsequence: ''
    }),

    preConfirm: () => {
      let strname = document.getElementById('strname').value;
      let intsequence = document.getElementById('intsequence').value;
 
      if (!strname) {
        Swal.showValidationMessage('The Department field is required.')
      }
      if (!intsequence) {
        Swal.showValidationMessage('The Sequence field is required.')
      }
      return {
        strname: document.getElementById('strname').value,
        intsequence: document.getElementById('intsequence').value
      }
    }
  }).then((result) => {
    if (result.isConfirmed) {
      let request = {
        strresourcename: "Richard",
        strapplicationcode: "SchoolApp",
        strmodulename: "Department",
        strtablename: "fmDepartments",
        strfieldid: "fmDepartmentsId",
        strname:document.getElementById('strname').value,
        intsequence:document.getElementById('intsequence').value
      }
      addDepartment(request).then(function(res){
        if (res.status == 200){
          Swal.fire({
            icon: 'success',
            title: 'Department',
            text: 'New Department has been added successfully.',
          }).then((res) => {
            setRerender(!reRender);
          })
        }else{
          Swal.fire({
            icon: 'error',
            title: 'Oops',
            text: 'Something went wrong.',
          })
        }
      })
          
    }
  })
}
class CustomToolbar extends React.Component {
  
  handleClick = () => {
    console.log("Add User Initiated...");
  }

  render() {
    const { classes } = this.props;

    return (
      <React.Fragment>
        <Tooltip title={"Add"}>
            <Button
              variant="contained"
              color="primary"
              size="small"
              style={{
                textTransform: 'unset',
                outline: 'none',
                marginLeft: 20,
                backgroundColor: '#00B029',
              }}
              onClick={HandleAdd}
              className={classes.button}
              startIcon={<AddIcon className={classes.addIcon} style={{color: '#fff',}} />}
            >
              Add
            </Button>
        </Tooltip>
      </React.Fragment>
    );
  }

}

export default withStyles(defaultToolbarStyles, { name: "CustomToolbar" })(CustomToolbar);

依赖

{
  "name": "@group1/school-template",
  "version": "3.2.1",
  "description": "School Access Management System",
  "author": {
    "github": "https://github.com",
    "twitter": "https://twitter.com"
  },
  "contributors": [
    {
      "name": "Group1 Team",
      "url": "https://github.com"
    }
  ],
  "homepage": ".",
  "copyright": "Copyright Richard M.",
  "license": "MIT",
  "private": true,
  "repository": {
    "type": "git",
    "url": "git@github.com"
  },
  "dependencies": {
    "@coreui/chartjs": "^2.0.0",
    "@coreui/coreui": "^3.4.0",
    "@coreui/icons": "^2.0.0",
    "@coreui/icons-react": "^1.1.0",
    "@coreui/react": "^3.4.6",
    "@coreui/react-chartjs": "^1.1.0",
    "@coreui/utils": "^1.3.1",
    "@date-io/date-fns": "^1.3.13",
    "@date-io/moment": "^1.3.13",
    "@material-ui/core": "^4.11.4",
    "@material-ui/icons": "^4.11.2",
    "@material-ui/lab": "^4.0.0-alpha.58",
    "@material-ui/pickers": "^3.3.10",
    "@syncfusion/ej2-react-calendars": "^19.2.47",
    "@wojtekmaj/enzyme-adapter-react-17": "^0.6.0",
    "axios": "^0.21.1",
    "classnames": "^2.2.6",
    "core-js": "^3.9.1",
    "date-fns": "^2.22.1",
    "downshift": "^3.4.8",
    "enzyme": "^3.11.0",
    "filter-material-ui": "^2.7.0",
    "formik": "^2.2.9",
    "lodash": "^4.17.21",
    "match-sorter": "^4.2.1",
    "material-ui-filter": "^3.1.3",
    "moment": "^2.29.1",
    "mui-datatables": "^3.7.7",
    "nanoid": "^3.0.0",
    "prop-types": "^15.7.2",
    "react": "^17.0.2",
    "react-app-polyfill": "^2.0.0",
    "react-bootstrap-sweetalert": "^5.2.0",
    "react-date-range": "^1.3.0",
    "react-dom": "^17.0.2",
    "react-dual-listbox": "^2.1.2",
    "react-multi-select-component": "^4.0.3",
    "react-multiselect-checkboxes": "^0.1.1",
    "react-redux": "^7.2.3",
    "react-router": "^5.2.0",
    "react-router-dom": "^5.2.0",
    "react-virtualized": "^9.22.3",
    "redux": "^4.0.5",
    "sass": "^1.32.8",
    "sweetalert2": "^11.0.20",
    "sweetalert2-react-content": "^4.1.1",
    "yup": "^0.32.9"
  },
  "devDependencies": {
    "@babel/core": "^7.13.14",
    "auto-changelog": "~2.2.1",
    "react-scripts": "^4.0.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "test:cov": "npm test -- --coverage --watchAll=false",
    "test:debug": "react-scripts --inspect-brk test --runInBand",
    "eject": "react-scripts eject",
    "changelog": "auto-changelog --starting-version 3.0.0 --commit-limit false --hide-credit"
  },
  "bugs": {
    "url": "https://ncfsolutionsinc.com"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 10",
    "not op_mini all"
  ],
  "jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx}",
      "!**/*index.js",
      "!src/serviceWorker.js",
      "!src/polyfill.js"
    ]
  },
  "engines": {
    "node": ">=10",
    "npm": ">=6"
  }
}

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您不能在非功能组件中使用useState。您在一个名为HandleAdd 的方法中使用它。 HandleAdd 不是组件!您正在使用分类组件。您需要将HandleAdd 移动到您的组件中,并使用类组件自己的statesetState

    class CustomToolbar extends React.Component {
      state = false;
      constructor(props) {
         super(props)
         this.HandleAdd = this.HandleAdd.bind(this);
      }
      HandleAdd = () => {
      Swal.fire({
        title: 'Add Department',
        text: "Input department name below.",
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Save',
        html: generateInputForms({
          strname: '',
          intsequence: ''
        }),
    
        preConfirm: () => {
          let strname = document.getElementById('strname').value;
          let intsequence = document.getElementById('intsequence').value;
     
          if (!strname) {
            Swal.showValidationMessage('The Department field is required.')
          }
          if (!intsequence) {
            Swal.showValidationMessage('The Sequence field is required.')
          }
          return {
            strname: document.getElementById('strname').value,
            intsequence: document.getElementById('intsequence').value
          }
        }
      }).then((result) => {
        if (result.isConfirmed) {
          let request = {
            strresourcename: "Richard",
            strapplicationcode: "SchoolApp",
            strmodulename: "Department",
            strtablename: "fmDepartments",
            strfieldid: "fmDepartmentsId",
            strname:document.getElementById('strname').value,
            intsequence:document.getElementById('intsequence').value
          }
          addDepartment(request).then(function(res){
            if (res.status == 200){
              Swal.fire({
                icon: 'success',
                title: 'Department',
                text: 'New Department has been added successfully.',
              }).then((res) => {
                this.setState(!this.state);
              })
            }else{
              Swal.fire({
                icon: 'error',
                title: 'Oops',
                text: 'Something went wrong.',
              })
            }
          })
              
        }
      })
    }
    
    
      handleClick = () => {
        console.log("Add User Initiated...");
      }
    
      render() {
        const { classes } = this.props;
    
        return (
          <React.Fragment>
            <Tooltip title={"Add"}>
                <Button
                  variant="contained"
                  color="primary"
                  size="small"
                  style={{
                    textTransform: 'unset',
                    outline: 'none',
                    marginLeft: 20,
                    backgroundColor: '#00B029',
                  }}
                  onClick={this.HandleAdd}
                  className={classes.button}
                  startIcon={<AddIcon className={classes.addIcon} style={{color: '#fff',}} />}
                >
                  Add
                </Button>
            </Tooltip>
          </React.Fragment>
        );
      }
    
    }
    

    【讨论】:

    • 是的,但是我该如何解决呢?
    • @kaito 已更新。请检查
    • 第 108:24 行:'HandleAdd' 未定义 no-undef
    • @kaito 已更新。因为我没有真正的代码。那是我的错误。您需要在方法调用之前使用this
    • 未处理的拒绝(TypeError):无法读取未定义的属性(读取“状态”)
    【解决方案2】:

    你不能在方法中使用钩子。它应该是一个功能组件

    这里HandleAdd是一个方法,而不是一个组件

    【讨论】:

    • 这与已经提供的答案有何不同?
    猜你喜欢
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2020-08-13
    相关资源
    最近更新 更多