REACT

在次之前接触的框架都是vue angularjs angular 都是双向绑定的。react 这个单项数据流,并且和别的框架设计思路完全不一样的框架 一点都没有接触过,正好现在时间充足可以看下,尝试下不同的东西。
因为是照着官网的教程和基础文档撸了一遍,所以这里就复制粘贴代码了,就说说收获吧。

收获

1、学习更多的es6知识,在看教程的过程中有一个super(),这是干啥的???

react 给出的解释是这样的: 在使用js class 时,你必须调用 super();方法才能在继承父类的子类中正确获取到类型的 this。
还是没看懂,于是花了1个多小时把阮一峰 es6中的class看了一遍 才搞懂着到底啥用。如果不调用super方法,子类就得不到this对象。 阮一峰的这个解释应该更符合 中国人说话方式。

2、this指向问题

this.handleClick = this.handleClick.bind(this); 为啥要写这句话?

下面是源码

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      
    );
  }
}

解释: 类的方法默认是不会绑定 this 的。如果你忘记绑定 this.handleClick 并把它传入 onClick, 当你调用这个函数的时候 this 的值会是 undefined

要bind(this)的原理:

var myObj = {

    specialFunction: function () {

    },

    anotherSpecialFunction: function () {

    },

    getAsyncData: function (cb) {
        cb();
    },

    render: function () {
        var that = this;
        this.getAsyncData(function () {
            // this.specialFunction() // 会报错 因为这里的this 指向 window
            // that.specialFunction();
               that.anotherSpecialFunction();
        });
    }
};
/* 同上
render: function () {
      this.getAsyncData(function () {
          this.specialFunction();
          this.anotherSpecialFunction();
      }.bind(this));
    }
*/
myObj.render();

感受

因为有angularjs 的基础,所以看vue 感觉很简单,react 目前感觉比 angular 简单点,但是需要学习新知识,还有就是组件化思想很好,值得深入学习一下。
下周找个react的项目学习一下。

你可能感兴趣的:(REACT)