1.useEffect的使用,渲染完毕就会触发的方法
import { useEffect,useState } from 'react';
/**
*
* @params1 副作用函数,在函数内部可以防止需要执行的操作
* @params2 数组,可选参数,在数组中放置依赖项,不同的依赖会影响前面函数的执行,
* 当是空数组的时候,副作用函数只会在组件渲染完毕后执行一次
* useEffect(()=>{},[])
* api : http://geek.itheima.net/v1_0/channels
*/
function App () {
const [count, setCount] = useState(0)
// useEffect 可选副函数依赖项
// 1.没依赖项 初始执行 + 组件更新就执行
// useEffect(() => {
// console.log('1.没有可选项时,组件每更新一次,就会执行一次复函数')
// })
// 2.只有初始执行
// useEffect(() => {
// console.log('2.可选项为空数组时,副函数只执行一次.就是页面渲染完成时执行')
// },[])
// 3.传入特定依赖项,初始执行+依赖项变化执行,这里是count变化就会执行
useEffect(() => {
console.log('3.特定依赖项目发生改变才会执行')
},[count])
return (
<div className="App">
<div>
count:{count}
<button onClick={()=>setCount(count+1)}>点击+1</button>
</div>
</div>
);
}
2.remove useEffect的副作用函数
卸载副作用就是 副作用函数中return ()=>{} 执行的函数
场景一般是卸载组件时,需要注销哪些监听器、定时器等
import { useEffect,useState } from 'react';
// useEffect函数 清除副作用中执行的函数
// 场景是 组件卸载时清除定时器等
function Son () {
useEffect(() => {
console.log('组件销毁卸载副作用')
var timer = setInterval(() => {
console.log('我当前在执行')
}, 1000)
// 卸载副作用就是 副作用函数中return ()=>{} 执行的函数
return ()=>{
clearInterval(timer)
}
},[])
return <div>我是子组件</div>
}
function App () {
const [IsShow, setIsShow] = useState(false)
return (
<div className="App">
<div>
{IsShow&&<Son></Son>}
<button onClick={() => setIsShow(!IsShow)}>{ IsShow?'卸载组件':'创建组件' }</button>
</div>
</div>
);
}
3.自定义hooks 抽离,封装
注意
-
只能在函数内部调用,不能再组件外使用
-
if for循环 或者条件渲染 内部 不能使用 hooks函数,只能在顶层使用
// 使用封装的hooks函数,多个函数之间的使用互不影响 function Son (props) { // 组件使用hooks函数 const { IsShow, changeIsShow} = useIsshow() return <div style={{display:'flex'}}> <button onClick={ changeIsShow}>{ IsShow?'隐藏':'显示' }</button> 我是子组件的数值:{IsShow&&<span style={{color:'skyblue'}}>{ props.count }</span>} </div> } // 抽离出来的通用hook 是否显示的hook function useIsshow () { // 1.通过useState定义双向绑定变量 const [IsShow, setIsShow] = useState(false) // 2.通过useState定义修改变量的回调函数 const changeIsShow = () => setIsShow(!IsShow) // 3.通过return 把需要暴露的变量或者回调函数暴露出去 return { IsShow, changeIsShow } } function App () { const { IsShow, changeIsShow} = useIsshow() const [count, setCount] = useState(0) return ( <div className="App"> <div style={{display:'flex'}}> <button onClick={ changeIsShow}>{ IsShow?'隐藏':'显示' }</button> <div>我是父组件的count {IsShow && <span style={{color:'red'}}>{count }</span>}</div> </div> <Son count={ count }></Son> </div> ); }