React基础之useMeno
React基础之useMeno
作用:在组件每次重新渲染的时候缓存计算的结果
import
{
useReducer
,
useState
}
from
“react”
;
function
fib
(
n
){
console
.
log
(
'
开始计算
'
);
if
(
n
<
3
){
return
1
}
return
fib
(
n
2
)+
fib
(
n
3
)
}
function
App
() {
const
[
count1
,
setCount1
]=
useState
(
0
)
const
[
count2
,
setCount2
]=
useState
(
0
)
const
result
=
fib
(
count1
)
return
(
<
div
className
=
“App”
this is app,
<
button
onClick
=
{
()
=>
{
setCount1
(
count1
1
)}
}
change count1:
{
count1
}
</
button
<
button
onClick
=
{
()
=>
{
setCount2
(
count2
1
)}
}
change count2:
{
count2
}
</
button
{
result
}
</
div
);
}
export default
App
;
此时我们点击count1或是count2都会重新计算fib
import
{
useMemo
,
useReducer
,
useState
}
from
“react”
;
function
fib
(
n
){
console
.
log
(
'
开始计算
'
);
if
(
n
<
3
){
return
1
}
return
fib
(
n
2
)+
fib
(
n
3
)
}
function
App
() {
const
[
count1
,
setCount1
]=
useState
(
0
)
const
[
count2
,
setCount2
]=
useState
(
0
)
const result = useMemo (() => {
// 返回计算得到的结果
return fib ( count1 )
},[ count1 ])
return
(
<
div
className
=
“App”
this is app,
<
button
onClick
=
{
()
=>
{
setCount1
(
count1
1
)}
}
change count1:
{
count1
}
</
button
<
button
onClick
=
{
()
=>
{
setCount2
(
count2
1
)}
}
change count2:
{
count2
}
</
button
{
result
}
</
div
);
}
export default
App
;
此时,只有count发生变化,result才会发生变化