美文网首页
Class vs Hooks

Class vs Hooks

作者: 玖肆seven | 来源:发表于2021-01-26 12:07 被阅读0次

State

//Class
class CounterButton extends Component {
    constructor() {
        super();
        this.state = {
            count: 0
        }
    }
    render() {
        return <button onClick={() => this.setState({ count: this.state.count + 1 })}>
            { this.state.count }
         </button>
    }
}

//Hooks
const CounterButton = props => {
    const [count, setCount] = useState(0);

    return <button onClick={() => setCount(count + 1)}>
            { count }
    </button>
}

ComponentDidMount

//Class
componentDidMount() {
    console.log('I just mounted!');
}

//Hooks
useEffect(() => {
    console.log('I just mounted!');
}, [])

ComponentWillUnmount

//Class
componentWillUnmount() {
    console.log('I am unmounting');
}

//Hooks
useEffect(() => {
    return () => console.log('I am unmounting');
}, [])

ComponentWillReceiveProps

//Class
componentWillReceiveProps(nextProps) {
    if (nextProps.count !== this.props.count) {
        console.log('count changed', nextProps.count);
    }
}

//Hooks
useEffect(() => {
    console.log('count changed', props.count);
}, [props.count])

ComponentDidUpdate

//Class
componentDidUpdate() {
    console.log('Just updated..');
}

//Hooks
useEffect(() => {
    console.log('Just updated...');
})

DOM refs

//Class
class InputWithFocus extends React.Component {
    constructor() {
        super();
        this.inputRef = null;
    }
    render() {
        return <>
            <input ref={inputRef => { this.inputRef = inputRef }} />
            <button onClick={() => this.inputRef.focus()}>
                Focus the input
            </button>
        </>
    }
}
//Hooks
const InputWithFocus = (props) => {
    const inputRef = useRef();
    return <>
        <input ref={inputRef} />
        <button onClick={() => inputRef.current.focus()}>
            Focus the input
        </button>
    </>
}
useRef除了DOM refs之外还有另一个很酷的用法,它也是一个通用容器,其当前属性是可变的,可以保存任何值,类似于类的实例属性。例如,要保留间隔id:
const Timer = (props) => {
    const intervalRef = useRef();

    useEffect(() => {
        const id = setInterval(() => {
            // ...
        });
        intervalRef.current = id;
        return () => {
            clearInterval(intervalRef.current);
        };
    });
}
一些生命周期方法,如componentdiddupdate,提供了以前的状态和属性。如果您真的需要之前的钩子值,可以通过以下方式进行模拟(再次使用我们的好朋友-useRef):
const Counter = props => {
    const [count, setCount] = useState(0);

    const prevCountRef = useRef();
    useEffect(() => {
        prevCountRef.current = count;
    });
    const prevCount = prevCountRef.current;

    return <h1>Now: {count}, before: {prevCount}</h1>;
}

ShouldComponentUpdate

我们将使用memo来实现这一点,虽然这不是一个钩子,但它仍然是类到功能组件迁移计划的一部分:
//Class
shouldComponentUpdate(nextProps) {
    return nextProps.count !== this.props.count
}

//memo
import React, { memo } from 'react';

const MyComponent = memo(
    _MyComponent, 
    // 注意条件与shouldComponentUpdate相反
    (prevProps, nextProps) => nextProps.count === prevProps.count

转自:http://www.cnblogs.com/daysme/

何以解忧 唯有学习

相关文章

  • Class vs Hooks

    State ComponentDidMount ComponentWillUnmount ComponentWil...

  • hooks

    简述 Hooks? hooks 是 React v16.7.0-alpha 加入的新特性,可以在 class 外使...

  • 剖析React Hooks底层源码

    Hooks API 类型 据官方声明,hooks 是完全向后兼容的,class componet 不会被移除,作为...

  • React Hooks的优缺点

    为什么要有 Hooks(Hooks 的优点) class 组件状态逻辑复用困难。只能通过 HOC 或者 rende...

  • 翻译练习react-hooks -1 (16.8.4)

    文章地址 版本:16.8.4 hooks介绍 hooks是react16.8新增的一个功能,它能让你在非class...

  • React Hooks用法详解(二)

    React Hooks 在了解React Hooks之前, 我们先看一下 Class 和函数式 的一般写法 Cla...

  • React 新特性 Hooks

    React Hooks 介绍 Hooks 是react16.8新增的,能让你不通过声明一个class来使用stat...

  • Class Component or React Hooks?

    这篇文章我将带着大家去初步了解下React hooks的一些知识。我们会从以下三个方面去了解、介绍React ho...

  • Instrumentation Test Framework

    Instrumentation Test Class VS JUnit Test Class 上面的代码给出的...

  • react hooks初探

    hooks是什么 hooks是react16.8版本中新增的特性,它让我们能够在不写class的情况下使用状态和其...

网友评论

      本文标题:Class vs Hooks

      本文链接:https://www.haomeiwen.com/subject/chlgzktx.html