React component class 的缺点
- 大型组件很难拆分和重构,也很难测试。
- 业务逻辑分散在组件的各个方法之中,导致重复逻辑或关联逻辑。
- 组件类引入了复杂的编程模式,比如 render props 和高阶组件。
React Hooks 的设计目的,就是加强版函数组件,完全不使用"类",就能写出一个全功能的组件。
Hooks are a way to write reusable code, instead of more classic techniques like inheritance
- useState ==> Function that lets you use state in a functional component
- useEffect ==> Function that lets you use something like lifecyle methods in a functional component
- 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
- When the component is rendered for the first time only
- when the component is rendered for the first time and whenever it rerenders
- 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
网友评论