简体   繁体   中英

Why is the setstate not updating the value in ReactJs?

I am using reactjs in my application. The currid_s is set to value -1 initially.. later after button click it is set to 2 but the timer doesnot show the updated value in the Console. Why? Here is the code

 
import React, { useState, useEffect } from "react";

export default function App() {
  const [currid_s, setcurrid_s] = React.useState(-1);
  const handless = () => {
    console.log("yess");
    setcurrid_s(2);
  };

  useEffect(() => {
    console.log(currid_s, "yes");
    getPosts();

    const interval = setInterval(() => {
      getPosts();
    }, 2000);

    return () => clearInterval(interval);
  }, []);

  // const all_pooo=()=>{
  //   console.log(curr,"dddd")
  // }
  const getPosts = async () => {
    console.log(currid_s);
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <button onClick={handless}>gggg</button>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Here is the link to code sandbox https://codesandbox.io/embed/beautiful-ardinghelli-dg1r4?file=/src/App.js&codemirror=1

You cannot get your new state value inside your setInterval because you're storing an old version of getPosts inside your interval callback function.

What happens is when currid_s updates, your App component rerenders, and a new getPosts function is initialized containing the new value. However, setInterval callback function stores a reference to an old getPosts function containing the old value. This old getPosts function would print the copy of the old currid_s value that was assigned upon mounting of the App component. Javascript does not support referencing of primitives, that's why your old getPosts function does not have the new value.

If you want to print your currid_s whenever it updates, just do this:

useEffect(() => {
  console.log(currid_s)
}, [currid_s])

You can change currid_s from a useState() to a useRef() so that its value is accessible from the closure that the setInterval callback captures:

 const { useRef, useEffect } = React; function App() { const currid_s = useRef(-1); const handless = () => { currid_s.current = 2; }; useEffect(() => { const getPosts = () => { console.log(currid_s.current); }; getPosts(); const interval = setInterval(() => { getPosts(); }, 2000); return () => { clearInterval(interval); }; }, []); return ( <div className="App"> <h1>Hello CodeSandbox</h1> <button onClick={handless}>Click me</button> <h2>Start editing to see some magic happen;</h2> </div> ). } ReactDOM,render(<App />. document;getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="root"></div>

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