简体   繁体   中英

How do I access the previous state in react hooks which the state is a string value

I'm having trouble accessing the previous state which is a string value.

    const [seat, selectSeat] = useState("");

I tried to use useRef, which is used to get the previous state of an integer value.

const prevSeatRef = useRef();
useEffect(() => {
    prevSeatRef.current = seat;
    console.log(seat , prevSeatRef.current);
  },[seat]); 

function currentSeatSelected() {
    if(prevSeatRef.current === ""){
        document.getElementById(seat).classList.add("selected");
    }
    else{
        document.getElementById(prevSeatRef.current).classList.remove("selected");
        document.getElementById(seat).classList.add("selected");
    }
}

However, this method when console logged, shows two same states. How can I fix this, or are there an alternative way to do this?

The useRef hook allows you to persist values between renders and accessing real DOM elements.

So, you can define another state and store the previous value. Then, in an event like clicking or etc., check the current and previous values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM