function app(){
const [count,setCount] = usestate(0)
const ref = useRef(0)
const increment = () =>{
setTimeOut(()=>{
setCount((ref.current += 1))
},1000)
}
return <h1 onClick={increment}>{count}</h1>
}
class App extends Component {
state ={
count:0
}
} //count是初始值 只执行一次
useRef 用于函数组件,ref.current 修改不会引发组件重新渲染
useEffect(()=>{},[]) 接收两个参数 执行的回调函数,依赖的数组
如果依赖数组为空,回调函数在每一次 componentDidMount 和 componentDid Update执行
如果依赖数组不为空,在依赖值每次更新渲染后执行,
如果不传依赖数组,每一次渲染结束后执行
function App(){
useEffect(()=>{
const handleScroll = () =>{
window.addEventListener("scroll", handleScroll);
return () => {
// 组件卸载之前执行
window.removeEventListener("scroll", handleScroll)
}
}
}, []};
useEffect(() => {
console.log("每次渲染结束都会执行")
});
useEffect(()=>{
console.log("只有在 count 变化后才执行")
}, [count])
}
类似mobx的reaction 和vue的 watch,只需关注依赖数据
const moveTo = (dom, delay,options) =>{
dom.style.transform = `translate(${options.x}px)`
dom.style.transition = `left${delay}ms`
}
const Animate = () =>{
const ref = useRef();
useEffect(() => {
moveTo(ref.current,500,{x:600})
},[])
return (
<div className="animate">
<div ref={ref}>方块</div>
</div>
)
}
const Animate = () => {
const ref = useRef();
useLayoutEffect(()=>{
moveTo(ref.current,500,{x:600})
},[])
}
useMemo 用法类似useEffect
const render = useMemo(()=>{
const dateTable: Moment[] = [];
const firstDayOfMonth = (defaultValue || moment()).clone();
firstDayOfMonth.date(1); //当月第一天
const day = firstDayOfMonth.day();
const lastMonthDiffDay = (day + 6) %7;
const lastMonth1 = firstDayOfMonth.clone();
lastMonth1.add(0 - lastMonthDiffDay - 1, 'days');
for(let i =0;i< DATE.DATE_COL_COUNT * DATE.DATE_ROW_COUNT;i++){
current = lastMonth1.clone().add(i,'days')
dateTable.push(current)
}
return dateTable;
},[defaultValue])
useCallback 指定依赖项,无关更新之后 取的还是上一次缓存起来的函数 常常配合React.memo一起做性能优化
跨组件取值
const Context = createContext(null)
function App(){
return (
<Context.Provider value={{ title:"hello,world" }}
<Child />
</Context.Provider>
)
}
function Child(){
const context = useContext(Context);
return <h1>{ context.title } </h1>
}
评论区