React 的体验

React 的体验

已经使用React js 有两年了。最近想了一下,这个React JS 有什么是自己发现了的特色之处呢?

this的问题

在使用ReactJS的时候发现this是一个非常有意思的东西,在class里面this是组件的本身。但是在函数的时候发现这个this就莫名其妙的undefined了。而且this的变量和函数有时候会冲突。如下代码

import React, { Component } from "react"

export default class MyComponent extends Component {

    constructor(props) {
        super(props);
        this.name="hello"
        this.getName="hhh"
    }

    getName=()=>{
        return "getName"
    }

    render(){
        return (
            
  • {this.name}
  • ); } }

    其中的 this.getName="hhh"把原来的Function getName()重新赋值了。一个解决方法就是代码规范去解决,对于函数使用_function_name来命名

    继承和组合问题

    React的代码基本是组合大于继承了,因为基本是组件化。为何是组件化大于继承的呢,因为组件强调的是props的,而且使用继承会导致之前的this问题,因为如果子类中也有this.state={}的语句会把父类的state覆盖掉,当然编程思想里面也有组合优于继承的说法。代码如下

    父类的name

    import React, { Component } from "react"
    
    export default class Father extends Component {
        constructor(props) {
            super(props);
    
            this.state = ({
                name: "father"
            });
        }
    
        render() {
            return 
    {this.state.name}
    } }

    子类继承了Father。

    import Father from "./Father"
    
    export default class Son extends Father {
        constructor(props) {
            super(props);
    
            this.state = ({
                sonName: "son",
                name:"som change"
            });
        }
    }
    
    

    把name改变了,悲剧的是如果子类的改为this.state = ({ sonName: "son"}),会把父类的name置空了。因为this.state重新赋值了。


    image.png

    JSON和Object

    JSON和Object是等价。也可以说是JSON是一个Object,所以json持有一个Function这个写法体现了巨大的语法优势。我们知道如果再C语言中有一种指针是函数指针,用于调用函数,在React中这个的实现开销更低了而且易于理解。

    你可能感兴趣的:(React 的体验)