Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

一个示例带你了解 React Hooks --- useMemo #387

Open
yangchch6 opened this issue Jul 19, 2020 · 0 comments
Open

一个示例带你了解 React Hooks --- useMemo #387

yangchch6 opened this issue Jul 19, 2020 · 0 comments

Comments

@yangchch6
Copy link

React useMemo 作用

useMemo 与 PureComponent 功能类似,都是使组件不会因为其他不相关的参数变化而重新渲染。
PureComponent 适用于 class 组件,useMemo 适用于 Function 组件。另外 React.useMemo 可以指定一个参数,只有当这个参数改变时,才会重新渲染组件。

如何使用

import React, {useMemo, useState} from 'react'

function Child (props) {
  const showNumber = () => {
    console.log('========render========')
    return (
      <div>
        <p>number is : {props.number}</p>
      </div>
    )
  }
  return useMemo(showNumber, [])
}

export default () => {
  const [count, setCount] = useState(0)
  return (
    <>
      <p>{count}</p>
      <button onClick={() => setCount(count+1)}>Click me!</button>
      <Child number={count}/>
    </>
  )
}

上面这段代码中,我们用 useMemo 处理了 Child 函数组件,useMemo 的第二个参数数组内,可以放入你改变数值就重新渲染 Function Component 的对象。如果[]为空就是只渲染一次,无论 props 发生什么变化,之后都不会渲染。
运行上面这段代码,我们会发现,Child 组件只在第一次渲染的时候,执行了一次 showNumber 方法,之后无论点击多少次 button 按钮,Child 都不会再重新渲染。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant