React Class功能与Hooks等效项

北城余情 提交于 2020-04-16 07:27:24

【推荐阅读】微服务还能火多久?>>>

React Class功能与Hooks等效项

https://medium.com/soluto-engineering/react-class-features-vs-hooks-equivalents-745368dafdb3

I gave a talk during a recent meetup at Soluto HQ — Intro to React Hooks.
While preparing for the presentation, I fell completely in love with Hooks.
Although I was skeptical at first glance, I quickly realized how easy it is to use them and how they make perfect sense.
You can really tell how much thought was put into the API and how it solves real life problems.
You can find a video of my talk attached to this post (Hebrew only… Sorry!).
In my talk I explained why we need Hooks, how they work, went over the core Hooks (useState, useEffect, useRef and useContext) and showed how to convert some of the class features into Hooks.
I also covered some other new features — memo, lazy and Suspense.
If you don’t speak Hebrew or just prefer reading over watching, I made a TL:DW (kind of a cheat sheet) on class features vs. Hooks. Enough intros… Let’s jump right to business!






最近在Soluto HQ的一次聚会上,我做了一个演讲-React Hooks简介。
在准备演示文稿时,我完全爱上了Hooks。
尽管乍一看我对此表示怀疑,但我很快意识到使用它们很容易,并且它们具有完美的意义。
您真的可以说出API投入了多少思想,以及它如何解决现实生活中的问题。
您可以在这篇文章中找到我的演讲视频(仅希伯来语……对不起!)。
在我的演讲中,我解释了为什么我们需要Hook,它们如何工作,遍历了核心Hook(useState,useEffect,useRef和useContext),并展示了如何将某些类功能转换为Hook。
我还介绍了其他一些新功能-备忘录,懒惰和挂起。
如果您不会讲希伯来语,或者只是喜欢看书而不是看书,那么我对课堂功能vs. Hooks做了TL:DW(备忘单)。 足够的介绍…让我们开始吧!






Class features vs. Hooks equivalents

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 \ ComponentDidUpdate

//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])


//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>
    </>
}

this.myVar

useRef has another cool usage besides DOM refs, it is also a generic container whose current property is mutable and can hold any value, similar to an instance property on a class.
Handy, for example, to keep an interval id:

const Timer = (props) => {
    const intervalRef = useRef();

    useEffect(() => {
        const id = setInterval(() => {
            // ...
        });
        intervalRef.current = id;
        return () => {
            clearInterval(intervalRef.current);
        };
    });
}

Comparing with the previous state\props

Some lifecycle method, like componentDidUpdate, provide the previous state and props.
If you really need the previous values for your Hooks, this can be imitated the following way (using yet again our good friend — 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

We gonna use memo for this one, while this is not a Hook, it’s still part of the class-to-functional-component migration plan:

//Class
shouldComponentUpdate(nextProps) {
    return nextProps.count !== this.props.count
}

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

const MyComponent = memo(
    _MyComponent, 
    // Notice condition is inversed from shouldComponentUpdate
    (prevProps, nextProps) => nextProps.count === prevProps.count

And that is React Hooks in a nutshell. I hope you will find this helpful when writing your next functional component.
Needless to say (but I’ll say it anyway), there are a whole lot more interesting and cool ways to use Hooks. I urge you to read the awesome overview the React team posted. Don’t miss out the FAQ section!
Last but not least, here’s me in my meetup video about React Hooks.
Watch, Like, Subscribe 😉


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!