React hooks 对应 ClassComponent 中的生命周期与 api

栏目: IOS · Android · 发布时间: 6年前

useEffect 可以代替的生命周期为 componentDidMount , componentWillUnMountcomponentDidUpdate

使用 useEffect 完成 componentDidMount 的效果

function AComponent() {
    useEffect(() => {
        // TODO
    }, []);
}
复制代码

useEffect 的第二个参数为 [] 时,表示这个effect只会在 componentDidMountcomponentWillUnMount 的时候调用

componentWillUnMount 调用的是第一个参数返回的回调

使用 useEffect 完成 componentDidUpdate 的效果

function AComponent({source}) {
    useEffect(() => {
        const subscription = source.subscribe();
        // TODO
        return () => {
          subscription.unsubscribe();
        };
    }, [source]); // 表示source改变时就是执行一遍
}
复制代码

forceUpdate

function AComponent() {
    const [ignored, forceUpdate] = useReducer(x => x + 1, 0);

    function handleClick() {
        forceUpdate();
    }
}
复制代码

getDerivedStateFromProps

function ScrollView({row}) {
    let [isScrollingDown, setIsScrollingDown] = useState(false);
    let [prevRow, setPrevRow] = useState(null);
    
    if (row !== prevRow) {
        // Row changed since last render. Update isScrollingDown.
        setIsScrollingDown(prevRow !== null && row > prevRow);
        setPrevRow(row);
    }
    
    return `Scrolling down: ${isScrollingDown}`;
}
复制代码

获取之前的 propsstate

function Counter() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);
  return <h1>Now: {count}, before: {prevCount}</h1>;
}

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}
复制代码

以上所述就是小编给大家介绍的《React hooks 对应 ClassComponent 中的生命周期与 api》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Impractical Python Projects

Impractical Python Projects

Lee Vaughan / No Starch Press / 2018-11 / USD 29.95

Impractical Python Projects picks up where the complete beginner books leave off, expanding on existing concepts and introducing new tools that you’ll use every day. And to keep things interesting, ea......一起来看看 《Impractical Python Projects》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

随机密码生成器
随机密码生成器

多种字符组合密码