简体   繁体   中英

React function doesn't updated with state

I'm trying to execute a function that is using react state but when state changes the function doesn't updates with the state value.

    const {useState, useEffect} = React;

function Example() {
  const [count, setCount] = useState(0);
  
  const testFunction = function(){
        setInterval(() => {
        console.log(count)
    }, 3000)
  }
  useEffect(() => {
let fncs = [testFunction];

fncs.forEach(fnc => fnc.apply(this));
  }, [])
  


  // Similar to componentDidMount and componentDidUpdate:  
  useEffect(() => {   
    // Update the document title using the browser API    
    document.getElementById('other-div').innerHTML = `You clicked ${count} times`;  
  });
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

ReactDOM.render( <Example />, document.getElementById('root') );

Exmaple: https://jsfiddle.net/bzyxqkwt/4/

just so you understand, im passing functions to another component and he execute those functions on some event like this

fncs.forEach(fnc => fnc.apply(this, someEventParams));

I'm just guessing that the setInterval is just for demo purposes and needs to be stopped/removed, but basically useEffect captures the initial state. So if you want to catch inside the inner function updated state, then you should pass all the values that you need (in this case count parameter). Something like:

const testFunction = function(){
    // setInterval(() => {
        console.log(count); // it should log the updated value
    // }, 3000)
  }
  useEffect(() => {
     let fncs = [testFunction];

      fncs.forEach(fnc => fnc.apply(this));
  }, [count]);   // <-- this makes the trick

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