useCallback

2020-08-14  本文已影响0人  一土二月鸟
// 示例1
import React from 'react';
import ReactDOM from 'react-dom';
import { useState } from 'react';
import { useCallback } from 'react';

const App = () => {

  const [age, setAge] = useState(0);
  const [said, setSaid] = useState('我可以玩');

  const cb = useCallback(() => {
    console.log(age, said);
    if (age > 3) {
      setSaid("我得上学了");
    }
  }, [age, said]);

  const clickPassYear = () => {
    setAge(age + 1);
    cb();
  }

  return (
    <>
      小爷今年{age}岁了,{said}
      <br />
      <button onClick={clickPassYear}>过去一年</button>
    </>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));
import React, { useCallback, useState, useEffect } from 'react';
import ReactDom from 'react-dom';

function Index () {

  const [count, setCount] = useState(0);


  const cb = useCallback(() => {
    setCount(count => count + 1); // 2. 此函数形成的闭包所持有的count永远是0,因为setCount后,函数会重新执行生成新的count,和闭包中的count是两个不同的值。
  }, []); // 1.此处为空数组,则cb只会被生成一次

  return <>
    <p>{count}</p> 
    <button onClick={cb}>click cb</button>
  </>

}

ReactDom.render(<Index />, document.getElementById('root'));
上一篇 下一篇

猜你喜欢

热点阅读