由于Hooks出来之后,我们可以采用函数组件创建复杂组件,但是失去了
shouldComponentUpdate
所以无法判断前后状态是否更新了。
在函数组件中 生命周期不存在mount
和和update
两个状态,也就是说函数组件每次调用都会执行内部的所有逻辑,这样会带来很大的性能损耗。所以useMemo
和useCallback
出现了
父组件
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16import { useState, Fragment } from 'react'; import Children from './Children' const index = () => { const [count, setCount] = useState(1) const [content, setContent] = useState('Lee') return ( <Fragment> <Children count={count} content={content} /> <button onClick={() => setCount(count + 1)}>+1</button> <button onClick={() => setContent(new Date().getTime())}>时间</button> </Fragment> ); }; export default index
子组件
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20const index = ({ count, content }) => { const expensive = () => { console.log(count, content); let sum = 0; for (let i = 0; i < count * 100; i++) { sum += i; } return sum; } return ( <> <h1>{count}--{content}--{expensive()}</h1> </> ) }; export default index
我们这边创建了两个state
然后通过expensive
这个函数对count
状态进行计算,我们会发现当我修改了任意一个状态的时候都会用调用这个expensive
函数。当修改content
发生改变的时候就没必要执行了。这个时候需要用到useMemo
useMemo
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23import { useMemo } from 'react'; const index = ({ count, content }) => { // !useMemo返回缓存的变量 const expensive = useMemo(() => { console.log(count, content); let sum = 0; for (let i = 0; i < count * 100; i++) { sum += i; } return sum; }, []); // ! 如若没参数 则更新 state 不会渲染 如果有参数 参数发生改变的时候才会执行此函数 与 useEffect 有着异曲同工之妙 但是 useEffect 有副作用 return ( <> <h1>{count}--{content}--{expensive}</h1> </> ) }; export default index
最后
以上就是秀丽舞蹈最近收集整理的关于React:useMemo的全部内容,更多相关React内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复