import { useState, useMemo, useCallback, useEffect, useRef } from 'react'
const Count = ({data}) => {
// 此处传进来的Props-data作为自变量作用于视图
return <i>{data}</i>
}
export const CsvExcel = () => {
const [x, setX] = useState(0) // 自变量
const y = x * 2 + 1 // 因变量
// 固定的输入一定会产生固定的输出
const changeX = () => setX(x+1)
// useRef在路径中起到缓存数据的作用,不是因变量,也不是自变量,为了让组件逻辑更灵活
const renderCounteRef = useRef(1)
const isOdd = renderCounteRef.current % 2 !== 0
renderCounteRef.current++
console.log('isOdd', renderCounteRef.current, isOdd)
// useMomo定义无副作用因变量
// 缓存因变量,依赖项为自变量x, x不变始终读取缓存的值, 不使用时每次函数组件会基于x重新生成新的y值
// const y = useMemo(() => 2 * x + 1, [x])
// useCallback定义无副作用因变量
// 缓存函数类型因变量,依赖项为自变量x,changeX原理同上
// const changeX = useCallback(() => setX(x), [x])
// 但引入随机数z之后输出就不固定了,这个函数就是包含副作用的
const calc = (x) => {
const z = Math.random();
return 2 * x + 1 + z
}
// useEffect定义含副作用的因变量
// x变化后触发函数变化
// 自变量x导致因变量变化后,因变量不仅可以作用于视图,也能触发副作用
useEffect(() => {
document.title = x
}, [x])
return (
<ul onClick={changeX}>
{isOdd ? <li><Count data={x}></Count></li> : null}
<li><Count data={y}></Count></li>
</ul>
)
}
フックの小さなケース
おすすめ
転載: blog.csdn.net/weixin_38318244/article/details/127263313
おすすめ
ランキング