美文网首页
React hooks

React hooks

作者: 柒轩轩轩轩 | 来源:发表于2021-05-11 02:38 被阅读0次

    React component class 的缺点

    1. 大型组件很难拆分和重构,也很难测试。
    2. 业务逻辑分散在组件的各个方法之中,导致重复逻辑或关联逻辑。
    3. 组件类引入了复杂的编程模式,比如 render props 和高阶组件。

    React Hooks 的设计目的,就是加强版函数组件,完全不使用"类",就能写出一个全功能的组件。

    Hooks are a way to write reusable code, instead of more classic techniques like inheritance

    1. useState ==> Function that lets you use state in a functional component
    2. useEffect ==> Function that lets you use something like lifecyle methods in a functional component
    3. useRef ==> Function that lets you create a 'ref' in a function component
    const [activeIndex, setActiveIndex]=useState(null)
    

    activeIndex --> piece of state
    setActiveIndex --> function to change piece of state
    null --> initial value for piece of state

    useEffect

    . Allows function components to use something like lifecycle methods

    . We configure the hook to run some code automatically in one of three scenarios

    1. When the component is rendered for the first time only
    2. when the component is rendered for the first time and whenever it rerenders
    3. when the component is rendered for the first time and (whenever it rerenders and some piece of data has changed)
    useEffect(()=>{},)
    

    after,
    [] ==> run at initial render
    nothing ==> run at initial render and run after every rerender
    [data]==> run at initial render and run after every rerender if data has changed since last render

    useEffect(()=>{
    console.log('1');
        return () =>{
          console.log('2');
        }
      },[term]
    )
    

    whenever our component first renders, the overall arrow function is invoked and we return the arrow function 2
    then anything when run the whole function again, first react is going to call the 2 functions that it got from the last time use effect ran, then it gonna call the overall function again

    当在dropdown component中,想要实现点击component外部从而实现dropdown的回缩
    使用manually click listener

    相关文章

      网友评论

          本文标题:React hooks

          本文链接:https://www.haomeiwen.com/subject/kfkbdltx.html