错误-挂钩只能在函数组件的主体内部调用

时间:2020-03-15 06:42:16

标签: reactjs react-hooks rollup rollupjs

我收到一个错误:Hooks can only be called inside the body of a function componen

在图像上,您可以看到我正在使用功能组件:http://prntscr.com/rgk36s

我的代码是使用汇总捆绑在一起的。

怎么了?

我的汇总配置为:

import { readdirSync } from 'fs';
import path from 'path';
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import external from 'rollup-plugin-peer-deps-external';
import pkg from './package.json';
import replace from 'rollup-plugin-replace';
import resolve from 'rollup-plugin-node-resolve';
import { terser } from 'rollup-plugin-terser';

const EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.json'];
const CODES = [
  'THIS_IS_UNDEFINED',
  'MISSING_GLOBAL_NAME',
  'CIRCULAR_DEPENDENCY',
];

const getChunks = URI =>
  readdirSync(path.resolve(URI))
    .filter(x => x.includes('.js'))
    .reduce((a, c) => ({ ...a, [c.replace('.js', '')]: `src/${c}` }), {});

const discardWarning = warning => {
  if (CODES.includes(warning.code)) {
    return;
  }

  console.error(warning);
};

const env = process.env.NODE_ENV;

const commonPlugins = () => [
  external({
    includeDependencies: true,
  }),
  babel({
    babelrc: false,
    presets: [['@babel/preset-env', { modules: false }], '@babel/preset-react'],
    extensions: EXTENSIONS,
    exclude: 'node_modules/**',
  }),
  commonjs({
    include: /node_modules/,
  }),
  replace({ 'process.env.NODE_ENV': JSON.stringify(env) }),
  resolve({
    extensions: EXTENSIONS,
    preferBuiltins: false,
  }),
];

export default [
  {
    onwarn: discardWarning,
    input: 'src/index.js',
    output: {
      esModule: false,
      file: pkg.unpkg,
      format: 'umd',
      name: 'myLibrary',
      exports: 'named',
      globals: {
        react: 'React',
        'react-dom': 'ReactDOM',
        'styled-components': 'styled',
      },
    },
    plugins: [...commonPlugins(), env === 'production' && terser()],
  },
  {
    onwarn: discardWarning,
    input: getChunks('src'),
    output: [
      { dir: 'esm', format: 'esm', sourcemap: true },
      { dir: 'cjs', format: 'cjs', exports: 'named', sourcemap: true },
    ],
    plugins: commonPlugins(),
  },
];

我不知道怎么了,您能帮我解决我的问题吗?看起来React没有与代码捆绑在一起。

  • 我正在尝试建立我的反应库

我的组件很简单:

import React, {useState} from 'react';

const Bar = () => {
    const [value, setValue] = useState(0)

    return (
        <button onClick={() => setValue(value + 1)}>
            {value}
        </button>
    )
}

export default Bar

按索引文件导出:export { default as Bar } from './Bar';


react-create-app中我组件的用法:

import * as React from 'react';
import './App.css'; 
import {Bar} from 'my-library';

function App () {
    return (
        <div className="App">
            <hr /> 
            <Bar />
        </div>
    );
}

export default App;

0 个答案:

没有答案