likes
comments
collection
share

Day 44/100 React Hook之useMemo基本用法

作者站长头像
站长
· 阅读数 17

(一)需求

最近在学习React,学到了React Hook 做了 useMemo Demo。

(二)介绍

使用useMemo是为了进而保留变量初始的值,并且依赖其他变量的改变后才更新的操作。

/*
 * @Author: ArdenZhao
 * @Date: 2022-04-20 11:18:24
 * @LastEditTime: 2022-04-20 11:36:50
 * @FilePath: /react-ts/src/components/react/12-Hook-useMemo.js
 * @Description: file information
 */
import { useState, useMemo } from 'react';
import { Button } from 'antd';
import "antd/dist/antd.css";


function HookUseMemo(props) {
  let [count, setCount] = useState(10);
  let [num, setNum] = useState(0);

  function changeCount() {
    setCount(count + 1);
  }

  function changeNum() {
    setNum(num + 1);
  }

  const memorized = useMemo(() => {
    return count;
  }, [num]);
  console.log('[ memorized ] >', memorized) //12-Hook-useMemo.js:31 [ memorized ] > 10
  // memorized中的count 的值没有随着count变化而,更新,作用是保留了初始count的值
  // 当点击按钮时,num的值会发生变化,memorized的值也会发生变化,但是count的值不会发生变化
  return (
    <div>
      <h1>Learn, {props.name}</h1>
      <p>Count:{count}</p>
      <Button onClick={changeCount}>Count加一</Button>
      <p>Num:{num}</p>
      <Button onClick={changeNum}>Num加一</Button>
    </div>
  );
}
export default HookUseMemo

写在最后的话

学习路上,常常会懈怠。

《有想学技术需要监督的同学嘛~》https://mp.weixin.qq.com/s/Fy...

如果有需要的伙伴,可以加我微信:learningisconnecting或者可以关注我的公众号:国星聊成长(我会分享成长的方法)
转载自:https://segmentfault.com/a/1190000041730613
评论
请登录