Модуль реагирующих компонентов 'classProperties' в настоящее время не включен - PullRequest
0 голосов
/ 29 июня 2019

получаю ошибку при выполнении моего реактивного модуля

classProperties в настоящее время не включен (44:11):

 }
  43 |   // componentDidUpdate or try this
> 44 |   onClick = (e) => {
     |           ^
  45 |     e.preventDefault();
  46 |      const url = `${this.props.url}`;
  47 |      if(this.props.method === "GET"){

Добавить @ babel / plugin-offer-class-properties (https://git.io/vb4SL) в раздел 'plugins' вашей конфигурации Babel для включения трансформации.

Я попробовал решения все еще получить ошибку после перестройки.

Поддержка экспериментального синтаксиса 'classProperties' в настоящее время не включена

package.json

{
  "name": "blahmodule",
  "version": "1.0.0",
  "description": "a fetch module for our project",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "./node_modules/.bin/babel src --out-file index.js"
  },
  "peerDependencies": {
    "react": "^16.6.6",
    "react-dom": "^16.6.3",
    "axios": "^0.19.0"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/cli": "^7.4.4",
    "@babel/core": "^7.4.5",
    "@babel/preset-env": "^7.4.5",
    "@babel/preset-react": "^7.0.0",
    "react": "^16.8.6",
    "react-dom": "^16.8.6"
  },
  "devDependencies": {
    "@babel/plugin-proposal-class-properties": "^7.4.4",
    "axios": "^0.19.0"
  }
}

.babelrc

Я попытался изменить .babelrc на babel.config.js с помощью module.exports, но все равно безуспешно. также с и без "loose": true

{
    "presets": [
      "@babel/preset-env",
      "@babel/preset-react"
    ],
    "plugins": [
        [
          "@babel/plugin-proposal-class-properties",
          {
            "loose": true
          }
        ]
      ]
  }

код с начала

import React, {Component} from 'react';
import axios from 'axios';

class MyFetch extends Component {
  constructor(props){
    super(props);
    this.state = {
      data:[],
      startTime:'',
      responseTime:''
    }

  }
  componentWillMount(){
   .....
  }
  // componentDidUpdate or try this
  onClick = (e) => {
    e.preventDefault();
     const url = `${this.props.url}`;
     if(this.props.method === "GET"){
        axios.get(url).then( res => {

          this.setState({
            data: res.data
          })
          console.log(this.state.data)
        })
     }
     else if(this.props.method === "POST"){
        axios.get(url).then( res => {
          this.setState({
            data: res.data
          })
          console.log(this.state.data)
        })
     }
  }
  render(){
    return (
      <div>
        {this.props.url ? (
         <button onClick={this.onClick}>Get Response Time</button>
          ):(
              null
          )}

       {this.state.responseTime ? (
         <h3>{this.state.responseTime}</h3>
       ):(
          null
       )}
       </div>
    );
  }
}

export default MyFetch;

Ответы [ 2 ]

0 голосов
/ 29 июня 2019

Исправлено добавлением webpack, я удалил .babelrc, потому что я включил в webpack.config.js .Теперь, я думаю, у меня есть причина использовать webpack в моих проектах.

var path = require('path');
module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, './'),
    filename: 'index.js',
    libraryTarget: 'commonjs2'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: path.resolve(__dirname, 'src'),
        exclude: /(node_modules|bower_components|build)/,
        use: {
          loader: 'babel-loader',
          options: { 
            presets: ['@babel/preset-env', '@babel/react'],
            plugins:['@babel/plugin-proposal-class-properties']
          }
        }
      }
    ]
  },
  externals: {
    'react': 'commonjs react',
    'reactDOM': 'react-dom'
  },
};
0 голосов
/ 29 июня 2019

Для начинающих лучший способ начать работать с React - использовать create-react-app для создания готового к использованию чистого шаблона.Посмотрите документы и не тратьте время на настройку, а сосредоточьтесь на написании кода для вашего приложения.

https://github.com/facebook/create-react-app#npm

...