React hooks

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容