React Hook useState 拿到更新后的值

4,988 阅读1分钟

React Hook 中 useState 是异步回调,set完无法立刻拿到值,遇到需要获取新值进行其他操作的时候,可以尝试下面方法

  1. 在useEffect中书写逻辑,[]中监听state改变。在useEffect中,组件dom已经挂载更新完毕,可以拿到state的最新值
import React, {useEffect, useRef, useState} from "react";

export default function Vendor() {
    const [count, setCount] = useState(0);
    useEffect(()=>{
    //需要使用最新值进行的操作
        console.log(count)
    },[count])

    return (

        <div>
            <p>点击了 {count} 次</p>
            <button onClick={() => {
                setCount(count+1)
            } }>
                点我
            </button>
        </div>
    );
}

2.setState中写成回调函数形式,可以取到最新的state, 回调函数中return的返回值即最新的state值

export default function Vendor() {
    const [count, setCount] = useState(0);
    return (
        <div>
            <p>点击了 {count} 次</p>
            <button onClick={() => {
                setCount(preCount=> {
                    console.log('更新前的state'+preCount)
                    //const newCount=1000
                    const newCount=preCount+1
                    console.log('更新后的state'+newCount)
                    return newCount
                })
            } }>
                点我
            </button>
        </div>
    );
}

3.useRef保存值。直接写在组件内部的对象,组件每次渲染都会生成一个和之前不一样的对象,useRef对象,可以确保组件每次渲染取到的都是同一个对象

export default function Vendor() {

    const countRef = useRef(null)
    const [count, setCount] = useState(0);
    useEffect(() => {//组件每次挂载完,countRef.current会存储上最新的值
        countRef.current = count
    }, [count])
    
    return (
        <div>
            <p>点击了 {count} 次</p>
            <button onClick={() => {
                countRef.current=count+1//countRef.current不随着组件每次渲染变化,先把新值存在这里
                setCount(count+1)
                console.log(countRef.current)//使用新值的逻辑
            } }>
                点我
            </button>
        </div>
    );
}