React HookApi

useEffect()

在开始新的更新前,React 总会先清除上一轮渲染的 effect。
如果不需要每次更新都执行,则传入第二个参数(依赖数组),只有当数组中的属性改变时才会调用

    useEffect(()=>{
        //组件加载或更新调用
        console.log("component did mount componentDidUpdate")
        //返回函数在组件卸载前调用
        return function cleanUp(){
            console.log("component  unmount");
        }
    },[ ]);//仅在xx属性更改时更新空数组([])只加载一次

useState

setState 函数用于更新 state。它接收一个新的 state 值并将组件的一次重新渲染加入队列

    const [state, setState] = useState(initialState);
    setState(newState);
//与 class 组件中的 setState 方法不同,useState 不会自动合并更新对象
    const [state, setState] = useState({})
    setState(preState => { return {...prevState, ...updatedValues} })

useReducer

和useState作用类似只是useReducer适用于逻辑较复杂且包含多个子值,或者下一个 state 依赖于之前的 state 等。

   //通过dispatch来更改状态,从而会调用switchState方法更新值
    const [state,dispatch]  = React.useReducer(switchState,{//初始值
        isLoading: true,
        isSignout: false,
        userToken: null,
    });
    function switchState(state,action){
        switch (action.type) {
            case 'RESTORE_TOKEN':
              return {
                ...state,
                userToken: action.token,
                isLoading: false,
              };
            //....
          }
    }
  //更新
  dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });

useMemo


    //传入 useMemo 的函数会在渲染期间执行,仅在依赖项改变时才会重新计算,
    //如果没有提供依赖项数组,useMemo 在每次渲染时都会计算新的值
    const memoValue = React.useMemo(()=>{return {} },[])

useContext && context

相当于 class 组件中的 static contextType = MyContext 或者 <MyContext.Consumer>。

  const ThemeContext = React.createContext(themes.light);
  const theme = useContext(ThemeContext);

在class组件中获取context值

  static contextType = ThemeContext
  // this.context.theme 获取值
posted @ 2021-06-30 10:59  菜鸟工程司  阅读(76)  评论(0编辑  收藏  举报