在React中有自带的hooks,也可以自己定义自定义hooks,所有的hooks都是以use开头–useXxx
解决了React函数组件中没有状态的问题
const FuntionComponent = () => {
// 如果想要设置相关的变量存储数据使用useState。useState调用后返回的是一个数组
// state 和 setState是自定义的名字 例如: a setA b setB
const [state, setState] = useState("默认值")
return (
<div>
{state}
<button onClick={() => setState('新的数据')}></button>
</div>
)
}
export default FunctionComponent
这个hook包含了created updated destroyed三个生命周期钩子函数
这个hook在一个组件中可以调用多次,所以尽可能将不同的请求放在不同的useEffect
created
function FunctionComponent () {
useEffect(() => {
// 这个函数只会执行一次
}, [])
}
updated(watch)
function FunctionComponent () {
useEffect(() => {
// 一旦数组中的值发生了改变,则会触发函数
}, [相关state的名字, 可以写多个])
}
destroyed
function FunctionComponent () {
useEffect(() => {
return () => {
// 这个函数会在组件被销毁时执行
}
}, [])
}
用来获取动态路由参数(vue this.$router.params)
import { useParams } from ‘react-router-dom’
const FuntionComponent = () => {
// 这个参数名和设置的动态路由的参数名一致 useParams调用后就是一个对象
const { 参数名 } = useParams()
}
可以获取路由相关信息
import { useLocation } from 'react-router-dom'
const FuntionComponent = () => {
const location = useLocation()
}
可以控制路由的跳转(相当于vue的编程式导航)
import { useHistory } from 'react-router-dom'
const FuntionComponent = () => {
const history = useHistory()
/
history.push('') 可以进行页面跳转
history.replace("") 跳转页面,会替换最新的记录
history.go()
/
}
react允许我们自己定义相关的hook,但是需要已 use 开头
我们自定义的hook可以用来获取query参数
function useQuery () {
return new URLSearchParams(useLocation().search)
}
useQuery().get('参数')