Class vs Hooks

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/

何以解忧 唯有学习
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。