๐
React 19 ใงใฏใใใผใฟๆดๆฐใจใใใซไผดใไธ้ฃใฎๆตใใใใพใๆฑใๆนๆณใจใใฆ Actions ใๅฐๅ ฅใใใใใใงใใ ไพใใฐใใใใพใงใใฉใผใ ใฎ้ไฟกไธญใฎ็ถๆ ใๆฌกใฎใใใซๆฑใใใจใใใใพใใใใใใใ React ใฎๆฉ่ฝใจใใฆๆจๆบๅใใใพใใ
const [isPending, setIsPending] = useState(false);
const submit = () => {
setIsPending(true);
await foo();
setIsPending(false);
}
return (
<form>
<button click={submit} disable={isPending}>foo</button>
</form>
)
ๆฐใใๅฐๅ
ฅใใใ Actions ใฎไธใคใงใใ useActionState
ใๅฉ็จใใฆๆธใใจๆฌกใฎใใใซๆธใใพใใ
const [error, submitAction, isPending] = useActionState(
async () => {
const error = await foo();
if (error) { return error; }
return null;
}
)
return (
<form action={submitAction}>
<button type="submit" disable={isPending}>foo</button>
</form>
)
Hook ใซๆธกใใ้ขๆฐใฏๅฎ่ณช็ใซ submitAction
ใฎๅ
ๅฎนใซใชใฃใฆใใฆใisPending
ใฏใใฎ้ขๆฐใฎๅฎ่ก็ถๆ
ใซๅใใใฆๅคใๅคๅใใพใใ
ใใใซใใฃใฆๆๅใฎใณใผใใจๅ็ญใซ isPending
ใไฝฟใฃใฆ UI ใฎ็ถๆ
ใๅคๆดใงใใใใจใใใใจใฎใใใงใใ
ใใใซ็ตใฟๅใใใฆไฝฟใใใใฎใจใใฆ useFormStatus
ใจใใ่ฆชใฎ form
ใฎๅฎ่ก็ถๆ
ใๅๅพใใใใจใๅบๆฅใ Hook ใใใใพใใใใใฏ react-dom ใใๆไพใใใใใฎใงใใ
ไพใใฐใใฟใณใณใณใใผใใณใใไฝใใจใใซใใฎ็ถๆ
ใๅคใใ Props ใจใใฆๆธกใใใจใใใใจๆใใพใใใ Actions ใไฝฟใฃใ form ใฎไธญใงใฏใใใ็ฐก็ฅๅใใใใจใๅบๆฅใพใใ
function FooSubmit() {
const { pending } = useFormStatus();
<button type="submit" disable={pending}>foo</button>
}
function FooForm() {
const [error, submitAction, isPending] = useActionState(
async () => {
const error = await foo();
if (error) { return error; }
return null;
}
)
return (
<form action={submitAction}>
<FooSubmit />
</form>
)
}
ใใใ useActionState
ใฎไพใจๅใๅไฝใซใชใใใใงใใ
Actions ใๅคฑๆใใใจใใซๅทปใๆปใใใ useState
ใฎใใใชใใฎใงใใๆฌกใซใณใผใใง await foo()
ใๅคฑๆใใใจใ value
ใ currentValue
ใซๆปใใพใใ
const [value, setValue] = useOptimistic('currentValue')
const [error, submitAction, isPending] = useActionState(
async () => {
setValue('newValue')
const error = await foo();
if (error) { return error; }
return null;
}
)>
ใฆใผใถใผๅใๅคๆดใใใใใ้่คใใงใใฏใซๆ้ใใใใใใใชๅ ดๅใซใ็ตๆใฎไบๅฎใๅ ใซ UI ใซๅๆ ใใฆใใใใใชๅ ดๅใซใใฎๅฎ่ฃ ใๆจๆบๅใงใใใใใงใใ