gnosis23 / hello-world-blog

还是 issues 里面写文章方便
https://bohao.work
0 stars 0 forks source link

React Hooks #53

Open gnosis23 opened 4 years ago

gnosis23 commented 4 years ago

感觉最近很多框架都准备上 Hooks 了,别人坑也踩的差不多了,是时候看起来了

看了一圈,原先很多 render props 和高阶组件的地方可以被替换了。

感觉用 Hooks 比较合适的例子:

关键函数:

gnosis23 commented 4 years ago

useRef

就像 class field 一样使用:可以理解 useRef 的值为引用,访问到的时候是最新的值;而像 useState 里面的值,访问到的时候就是当前的值。举个🌰如下:

如下在闭包中访问的时候,值为当前的值 0,而非最新值 100 。

export const MyComponent: React.FC<{}> = () => {
    const [value, setValue] = useState(0);
    const [anotherValue, setAnotherValue] = useState(0);

    useEffect(() => {
        window.setTimeout(() => {
            console.log('setAnotherValue', value) // 当保存闭包的时候 value 为 0
            setAnotherValue(value);
        }, 1000);
        setValue(100);
    }, []);

    return (
        <span>Value is {value}, AnotherValue is {anotherValue}</span>
    );
}

如果要达到目标,可以使用 useRef

function useCurrentValue(value) {
  const ref = useRef(null);
  ref.current = value;
  return ref;
}

export const MyComponent: React.FC<{}> = () => {
    const [value, setValue] = useState(0);
    const [anotherValue, setAnotherValue] = useState(0);
    const valueRef = useCurrentRef(value);

    useEffect(() => {
        window.setTimeout(() => {
            console.log('setAnotherValue', valueRef.current) // <- 100
            setAnotherValue(valueRef.current);
        }, 1000);
        setValue(100);
    }, []);

    return (
        <span>Value is {value}, AnotherValue is {anotherValue}</span>
    );
}

Reference

作者:小蘑菇哥哥 链接:https://juejin.im/post/5dad5020f265da5b9603e0ca