簡體   English   中英

為什么不能在函數中訪問更新的prop值?

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

所以我有一個功能組件,可以從redux獲取數據。 我的問題是,盡管數據在Redux存儲中正確更改,但我無法訪問某個道具的當前值,所以我認為Redux並不是問題。

我在下面重寫了我組件的一個簡單版本。 奇怪的是,即使在我的組件jsx中返回值.toString()也會返回正確的值,所以我希望這只是一個范圍問題,或者是我沒有得到我的代碼而沒有得到正確的值。

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);


這是我遇到的問題的CodeSandbox重新創建的鏈接。

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

setIntervalisPlaying之上創建一個閉包,這就是為什么它總是相同的值。

時間間隔保留對isPlaying的值的引用,它是通過with調用的。 要進行更改,您可能需要clearInterval並在isPlaying更改時開始一個新的isPlaying

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM