【问题标题】:Uncaught Invariant Violation: Hooks can only be called inside the body of a function componentUncaught Invariant Violation:钩子只能在函数组件的主体内部调用
【发布时间】:2019-03-09 09:55:23
【问题描述】:

正如标题中所说,我似乎无法使用挂钩

我知道你们中的一些人会尝试告诉我这是重复的,但在我看到的所有问题中,似乎没有人问使用导入的功能组件的正确方法是什么 我尝试渲染的组件。

    import React from 'react';
import { hot } from 'react-hot-loader';
import Playground from '../playground/index';

class App extends React.Component {
  render() {
    Playground();
    return (
      <div>
        <p>Hello World</p>
      </div>
    );
  }
}

export default hot(module)(App);

我的开发依赖:

我包括它们是因为我在其他答案中看到人们声称是由于版本(我已经更新了所有反应)

"devDependencies": {
    "sass-loader": "7.1.0",
    "sass": "*",
    "@babel/cli": "7.1.5",
    "@babel/core": "7.1.5",
    "@babel/plugin-proposal-class-properties": "7.1.0",
    "@babel/plugin-syntax-dynamic-import": "7.0.0",
    "@babel/preset-env": "7.1.5",
    "@babel/preset-react": "7.0.0",
    "babel-core": "7.0.0-bridge.0",
    "babel-eslint": "10.0.1",
    "babel-jest": "23.6.0",
    "babel-loader": "8.0.4",
    "babel-plugin-dynamic-import-node": "2.2.0",
    "css-loader": "1.0.1",
    "eslint": "5.12.0",
    "eslint-plugin-jsx-a11y": "6.1.2",
    "eslint-plugin-react": "7.12.3",
    "html-webpack-plugin": "3.2.0",
    "husky": "1.3.1",
    "jest": "23.6.0",
    "jest-dom": "2.1.1",
    "node-sass": "4.11.0",
    "node-sass-chokidar": "1.3.4",
    "prettier": "1.15.2",
    "pretty-quick": "1.8.0",
    "react-axe": "3.0.2",
    "react-testing-library": "5.2.3",
    "style-loader": "0.23.1",
    "webpack": "4.25.1",
    "webpack-bundle-analyzer": "3.0.3",
    "webpack-cli": "3.1.2",
    "webpack-dev-server": "3.1.10",
    "webpack-merge": "4.1.4"
  }

以及我尝试导入的功能组件:

import React, { useState } from 'react';

export default function Playground() {
  const [text, setText] = useState('');
  const [checked, setCheck] = useState(false);

  return (
    <section>
      <input type="text" value={text} onChange={e => setText(e.target.value)} />
      <input
        type="checkbox"
        value={checked}
        onChange={e => setCheck(e.target.value)}
      />
      <ul>
        <li>{text}</li>
        <li>{checked.toString()}</li>
      </ul>
    </section>
  );
}

【问题讨论】:

标签: reactjs import react-hooks


【解决方案1】:

使用函数组件的正确方法与使用类组件的正确方法没有什么不同。你不应该尝试调用你的组件函数——就像你不创建你的类的实例——你只是在你的 JSX 中使用它。

通过调用您的组件函数,您实际上将其视为返回 React 元素的自定义钩子(自定义钩子只是一个使用 React 的内置钩子的函数,如 useState)。这会导致 React 报错,因为您是从类组件的 render 方法而不是从函数组件的主体调用自定义钩子。

这是使用 Playground 组件的一种可能方式:

import React from 'react';
import Playground from '../playground/index';

class App extends React.Component {
  render() {
    return (
      <Playground/>
    );
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-06
    • 2019-11-21
    • 2020-10-27
    • 2021-10-31
    • 2020-01-28
    • 2020-02-14
    • 2021-02-08
    • 1970-01-01
    相关资源
    最近更新 更多