Vue与React的对比学习 - 02

React & Vue 技术分享

本次不是一门课程学习,仅仅只是个人对于两大框架的理解进行相应的对比分享。有错误和不对的地方望大佬指出。

作为一个程序员,任何时候,都不要瞧不起别人…鸟活着时,吃蚂蚁;鸟死后,蚂蚁吃鸟。一棵树可以制成一百万根火柴,烧光一百万棵树只需一根火柴。所以不要瞧不起任何人!你瞧不起别人时,只不过别人不和你计较!

  1. Vue 和 React 的进阶对比

  2. Vue 3.0 & React 16.8

  3. Vue 和 React 的进阶对比
    • Ref

      Vue和React中获取ref的方式是相同的,但是获取到的ref和写法有些许差异。

      VueReact
      this.$refs.examplethis.refs.example
      Vue获取Ref
      
      

​ React在18年是也迎来了自己的版本升级,该次升级也是变动比较大的一次升级,废弃了部分生命周期,新加入了部分生命周期,并且在16.7中引入了React Hooks

  1. render 支持返回数组和字符串
// 错误写法
class WrongDemo extends React.Component {
    render() {
         return (
            <h1>Welcome to React</h1>
            <div>Hello,Programmer</div>
        )
    }
}

// 正确写法
class Demo extends React.Component {
    render() {
         return [
            <h1>Welcome to React</h1>,
            <div>Hello,Programmer</div>
        ]
    }
}

  1. Error Boundaries - 抓错生命周期
class ErrorBoundary extends React.Component {
  state = { hasError: false };

  componentDidCatch(error, info) {
    this.setState({ hasError: true });

    logErrorToMyService(error, info);
  }

  render() {
    if (this.state.hasError) {
      return <h1>数据错误</h1>;
    }
    
    return this.props.children;
  }
}

  1. createPortal - 组件渲染到根节点
constructor(props){
    super(props)
    this.container = document.createElement('div');
    document.body.appendChild(this.container);
}

componentWillUnMount(){
    document.removeChild(this.container)
}

render(){
    return ReactDom.createPortals(
        <Model/>
        {this.container}
    )
}

  1. 支持自定义 DOM 属性

  2. Fragment -> 可以理解为Vue中的template

  3. createRef / forwardRef

    React.forwardRef 是 Ref 的转发, 它能够让父组件访问到子组件的 Ref,从而操作子组件的 DOM。 React.forwardRef 接收一个函数,函数参数有 props 和 ref。

  4. lazy / Suspense

    import React, {lazy, Suspense} from 'react';
    const OtherComponent = lazy(() => import('./OtherComponent'));
    
    function MyComponent() {
      return (
        <Suspense fallback={<div>Loading...</div>}>
          <OtherComponent />
        </Suspense>
      );
    }
    
    
  5. 生命周期函数的更新

    React 引入了 getDerivedStateFromProps 、 getSnapshotBeforeUpdate 及 componentDidCatch 等三个全新的生命周期函数。同时也将 componentWillMount、componentWillReceiveProps 和 componentWillUpdate 标记为不安全的方法。(标记为不安全就是后续会删除的生命周期)

    ​ [外链图片转存失败(img-j3cJGUMU-1565070149506)(D:\Work\Project\lesson\react-new-lifecycle.png)]

    getDerivedStateFromProps 代替 componentWillReceiveProps ,传入的props映射到state上面

    static getDerivedStateFromProps(nextProps, prevState) {
        const {type} = nextProps;
        // 当传入的type发生变化的时候,更新state
        if (type !== prevState.type) {
            return {
                type,
            };
        }
        // 否则,对于state不进行任何操作
        return null;
    }
    
    

​ getSnapshotBeforeUpdate 被调用于render之后,可以读取但无法使用DOM的时候。它使您的组件可以在可能更改之前从DOM捕获一些信息(例如滚动位置)。此生命周期返回的任何值都将作为参数传递给componentDidUpdate

​ componentDidCatch 页面级崩溃处理

  1. Hooks

之前的版本:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
 
  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

Hooks版本

import { useState } from 'react';
 
function Example() {
  const [count, setCount] = useState(0);
 
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

状态 - count

更新自己的状态 - setCount

在没有hooks之前,React的核心思想就是高度组件化,将一个页面拆成一堆独立的,可复用的组件,并且用自上而下的单向数据流的形式将这些组件串联起来。但假如你在大型的工作项目中用react,你会发现你的项目中实际上很多react组件冗长且难以复用。官方给出的解决方案就是: 渲染属性 & 高阶组件

  • 渲染属性 - 渲染属性指的是使用一个值为函数的prop来传递需要动态渲染的nodes或组件
    import Cat from 'components/cat'
    class DataProvider extends React.Component {
      constructor(props) {
        super(props);
        this.state = { target: 'Zac' };
      }
     
      render() {
        return (
          <div>
            {this.props.render(this.state)}
          </div>
        )
      }
    }
    
    <DataProvider>
      {data => (
        <Cat target={data.target} />
      )}
    </DataProvider>
    
    
  • 高阶组件 - 一个函数接受一个组件作为参数,经过一系列加工后,最后返回一个新的组件
    const withUser = WrappedComponent => {
      const user = sessionStorage.getItem("user");
      return props => <WrappedComponent user={user} {...props} />;
    };
     
    const UserPage = props => (
      <div class="user-container">
        <p>My name is {props.user}!</p>
      </div>
    );
     
    export default withUser(UserPage);
    
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值