简体   繁体   中英

Why can't I access the updated prop value within my function?

So I have a functional component that gets data from redux. My issue is, I'm not able to access the current value of a certain prop, though the data is changing correctly in the redux store so it isn't an issue with redux, I don't think.

I rewrote a simple version of my component below. Oddly enough, even returning the value .toString() in my component jsx returns the correct value so I'm hoping this is just some scope issue or something I'm not getting about my code that is not getting me the correct value.

const Player = ({ isPlaying }) => {

  function setProgress() {
    console.log(isPlaying) // returns false here continuously!
  }

  function playSong() {
    setInterval(() => {
      setProgress();
    }, 500);
  }

  useEffect(() => {
    console.log(isPlaying) // returns true here!
  }, [isPlaying])
}


const mapStateToProps = ({ isPlaying }) => {
  console.log(isPlaying); // also returns true here!
  return { isPlaying };
};

export default connect(mapStateToProps, null)(Player);


Here is a link to a CodeSandbox recreation of the problem I have.

https://codesandbox.io/s/playererrordemo-r6bt2

setInterval creates a closure over isPlaying , that's why it's always the same value.

The interval keeps the reference to the value of isPlaying , it was called with. To change that you might need to clearInterval and start a new one when isPlaying changes.

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