在react類組件中,有組件間可共享邏輯時(shí)导饲,一般用高階組件的方式對(duì)公共邏輯進(jìn)行復(fù)用集侯,在react函數(shù)組件中,hook提供了自定義hook函數(shù)的方案來對(duì)公共邏輯進(jìn)行復(fù)用帜消。
下面可以通過一段表單受控組件中創(chuàng)建value和onChange方法的重用案例來了解自定義hook的基本用法棠枉。
代碼如下:
import React, { useState } from 'react';
// 自定義hook(use開頭)
// 重用受控表單創(chuàng)建state和onChange方法邏輯
/**
*
* @param {string | number} initialValue 初始默認(rèn)值
* @returns
*/
const useInput = (initialValue) => {
const [value, setValue] = useState(initialValue)
return {
value,
onChange: e => setValue(e.target.value)
}
}
// 表單組件
const FormComponent = () => {
const username = useInput('admin')
const password = useInput('')
const onSubmit = (e) => {
e.preventDefault()
// 獲取表單值
console.log(username.value, password.value);
}
return (
<form onSubmit={onSubmit} >
<input type="text" {...username} />
<input type="password" {...password} />
<button type="submit">提交</button>
</form>
);
}
export default FormComponent;
很多組件當(dāng)中請(qǐng)求數(shù)據(jù)的方法也可以封裝為自定義hook函數(shù),供多個(gè)組件共用泡挺。
代碼如下:
import React, { useEffect, useState } from 'react';
import axios from 'axios'
// 自定義hook
// 封裝公共的請(qǐng)求邏輯并返回?cái)?shù)據(jù)
const usePosts = () => {
const [posts, setPosts] = useState('')
useEffect(() => {
getPosts()
}, [])
const getPosts = async () => {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts/1')
setPosts(data)
}
return [posts, setPosts]
}
const App = () => {
const [posts] = usePosts()
return (
<div>
<div>{posts.title}</div>
<div>{posts.body}</div>
</div>
);
}
export default App;