React useState未定义与webpack-dev-server一起使用

时间:2019-01-05 07:27:04

标签: javascript reactjs webpack-dev-server react-hooks

我正在使用React钩子和webpack-dev-server构建一个简单的react应用程序。我想启用热重装。

运行webpack-dev-server --mode development时,出现一个错误:TypeError: Object(...) is not a function,它在编译的下面一行中抱怨。

var _useState = Object(react__WEBPACK_IMPORTED_MODULE_0__["useState"])(0),

这是我的代码 webpack.config.js

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: './src/index.jsx',
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      }
    ]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx'],
    mainFiles: ['index']
  },
  output: {
    path: path.join(__dirname, 'public'),
    publicPath: '/',
    filename: 'bundle.js'
  },
  plugins: [new webpack.HotModuleReplacementPlugin()],
  devServer: {
    contentBase: './public',
    hot: true
  }
};

.babelrc

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
    "react-hot-loader/babel"
  ]
}

Body.jsx

import React, { useState } from 'react';

const Body = () => {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>{`You clicked ${count} times`}</p>
      <button type="button" onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
};

export default Body;

App.jsx

import React from 'react';
/* eslint-disable import/no-extraneous-dependencies */
import { hot } from 'react-hot-loader/root';
import { setConfig } from 'react-hot-loader';

import Body from './Body';

const App = () => (
  <div className="App">
    <Body />
  </div>
);

export default hot(App);

index.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
ReactDOM.render(<App />, document.getElementById('app'));

对于依赖关系,我正在使用带有版本16.7.0-alpha.2的react和react-dom。 react-hot-loader版本是4.6.3

1 个答案:

答案 0 :(得分:1)

不幸的是,react-hot-loader与钩子不兼容,据我所知及其问题github页面。 https://github.com/gaearon/react-hot-loader/issues/1088