简体   繁体   English

从ES5转换为ES6语法时,为什么我的代码不起作用?

[英]Why Doesn't My Code Work When Converting From ES5 To ES6 Syntax?

I'm new to React and working my way through how to use 'props' and 'state' in online course. 我是React的新手,并逐步学习如何在在线课程中使用“道具”和“状态”。 Online course uses ES5, but my IDE is set up for ES6. 在线课程使用ES5,但是我的IDE是为ES6设置的。 I've gotten through converting most examples just fine. 我已经完成了大多数示例的转换。 But the following is baffling. 但是以下令人困惑。 The example works fine, but my ES6 conversion doesn't--the page renders blank. 该示例工作正常,但我的ES6转换却不行-页面变为空白。 I looked through "Questions that may already have your answer", but nothing reveals my omission(s)/mistake(s). 我浏览了“可能已经有您答案的问题”,但没有发现我的遗漏/错误。 I was validated on other changes syntactically though. 尽管我在语法上对其他更改进行了验证。 :) :)


My conversion in 'App.js' file 我在“ App.js”文件中的转换

import React, { Component } from 'react';

let green = '#39D1B4';
let yellow = '#FFD712';

class Toggle extends Component {

  getInitialState() {
    return {color: green};
  }

  changeColor(){
    let newColor = this.state.color === green ? yellow : green;
    this.setState({color: newColor});
  }

  render() {
    return (
      <div style={{background: this.state.color}}>
        <h1>
          Change My Color
        </h1>
        <button onClick={this.changeColor}>
          Change Color
        </button>
      </div>
    );
  }
}

export default Toggle;

My conversion in 'index.js' file 我在“ index.js”文件中的转换

import React from 'react';
import ReactDOM from 'react-dom';
import Toggle from './App';

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);

'index.html' file 'index.html'文件

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Call 'this.setState' From Another Function</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

$ npm start says: $ npm start说:

Compiled successfully! 编译成功!

The app is running at: 该应用程序在以下位置运行:

http://localhost:3000/ http://本地主机:3000 /

Note that the development build is not optimized. 请注意,开发版本尚未优化。 To create a production build, use npm run build. 要创建生产版本,请使用npm run build。


Yes, I got the following from the Console: 是的,我从控制台获得了以下信息:

Warning: getInitialState was defined on Toggle, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?
printWarning @ warning.js:36
App.js:20Uncaught TypeError: Cannot read property 'color' of null
    at Toggle.render (App.js:20)
    at ReactCompositeComponent.js:796
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795)
    at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:362)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
    at Object.mountComponent (ReactReconciler.js:46)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:371)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
content.js:4186 Uncaught TypeError: Cannot read property 'indexOf' of null
    at content.js:4186

Looks like everything works fine after adding a constructor, binding the method and fixing the onClick syntax. 在添加构造函数,绑定方法并修复onClick语法后,看起来一切正常。 Direction is appreciated. 方向表示赞赏。 Thanks. 谢谢。

Three things: 三件事:

  1. There is no getInitialState in ES6-style React components. ES6风格的React组件中没有getInitialState Set the state in the constructor of Toggle : Toggle的构造函数中设置状态:

     constructor(props) { super(props); this.state = { color: green }; } 
  2. React does not automatically bind component methods to this in ES6-style components. 在ES6样式的组件中,React不会自动将组件方法绑定this方法。 So, when you do onClick={this.changeColor} , and the onClick callback is triggered, this will be null , causing another error. 因此,当您执行onClick={this.changeColor}并触发onClick回调时, this将为null ,从而导致另一个错误。 Fix this by binding this.changeColor to this in the constructor: 通过结合修复此this.changeColorthis在构造函数:

     constructor(props) { super(props); this.state = { color: green }; this.changeColor = this.changeColor.bind(this); } 

    Alternatively, use an ES6-style arrow function for onClick : onClick={() => this.changeColor()} 或者,对onClick使用ES6风格的箭头功能: onClick={() => this.changeColor()}

  3. Your index.html doesn't include your script. 您的index.html不包含您的脚本。 This may just be a copy-paste error in your question, but make sure you include your script: 这可能只是您问题中的复制粘贴错误,但请确保包含脚本:

     <script src="index.js"></script> 

I don't see that this would cause no rendering, but you cannot use getInitialState() in React class components. 我看不到这不会导致任何渲染,但是您不能在React类组件中使用getInitialState()。 You need to use the constructor of the class to do it: 您需要使用该类的构造函数来做到这一点:

import React, { Component } from 'react';

let green = '#39D1B4';
let yellow = '#FFD712';
class Toggle extends Component {

  constructor() {
    super();
    this.state = {
      color: green
    }
  }

  changeColor(){
    let newColor = this.state.color === green ? yellow : green;
    this.setState({color: newColor});
  }

  render() {
    return (
      <div style={{background: this.state.color}}>
        <h1>
          Change My Color
        </h1>
        <button onClick={this.changeColor}>
          Change Color
        </button>
      </div>
    );
  }
}

export default Toggle;

There's no getInitialState() when you use a class . 使用class时没有getInitialState() For that, set the initial state in the constructor: 为此,请在构造函数中设置初始状态:

class SomeComponent extends Component {
  constructor(props) {
    super(props);

    // Define initial state here
    this.state = {
      color: '#39D1B4'
    };
  }
  // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM