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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Charlotte's Web

Charlotte's Web

E. B. White / Puffin Classics / 2010-6-3 / GBP 6.99

This is the story of a little girl named Fern who loved a little pig named Wilbur and of Wilbur's dear friend, Charlotte A. Cavatica, a beautiful large grey spider. With the unlikely help of Templeton......一起来看看 《Charlotte's Web》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具