Hooks是一个新的React特性提案,组件尽量写成纯函数,如果需要外部React特性(比如状态管理,生命周期),就用钩子把外部特性"钩"进来,通常函数名字都是以use开头。首次在v16.7.0-alpha版本中添加,在v16.8.0中正式发布它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性。
importReact ,{useState}from'react'
useState: 函数组件里面没有state,所以我们使用useState,只接受一个参数,就是该state属性的初始值,它会返回一个数组,里面包含两个值,第一个值是初始值,第二个用来更改初始值。
useEffect: 函数式组件没有生命周期,使用useEffect来替代componentDidMount和componentDidUpdate。有两个参数,第一个是一个回调函数,第二个是空数组。如果第二个数组为空数组,就会在初始化执行完成之后,执行一次,相当于componentDidMount,数组有内容,会根据数组内容改变去执行前面的回调函数。相当于componentDidUpdate生命周期。
userContext: 组件之间共享状 https://blog.csdn.net/weixin_43606158/article/details/100750602
useReducer: 相当于简单的redux。接收两个参数,第一个参数是一个回调函数,里面接收一个state数据,以及action,通过dispatch来更改内容。第二个参数是一个初始值。
const initialState = { count1:0, count2:0,};const reducer = (state, action) => { switch (action.type) { case 'increment1': return { ...state, count1:state.count1 +1}; case 'decrement1': return { ...state, count1:state.count1 -1}; case 'set1': return { ...state, count1: action.count }; case 'increment2': return { ...state, count2:state.count2 +1}; case 'decrement2': return { ...state, count2:state.count2 -1}; case 'set2': return { ...state, count2: action.count };default: throw new Error('Unexpected action'); }
constExample02 =()=>{const[state, dispatch] = useReducer(reducer, initialState);return(<>
useCallback: 传入两个参数,第一个是回调函数,第二个是依赖,这个回调函数只在某个依赖改变时才会更新。
useMemo: 可以优化用以优化每次渲染的耗时工作。
useRef: 它可以用来获取组件实例对象或者是DOM对象,来跨越渲染周期存储数据,而且对它修改也不会引起组件渲染。