[英]Why can't I access the updated prop value within my function?
So I have a functional component that gets data from redux. 所以我有一个功能组件,可以从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.
我的问题是,尽管数据在Redux存储中正确更改,但我无法访问某个道具的当前值,所以我认为Redux并不是问题。
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.
奇怪的是,即使在我的组件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);
Here is a link to a CodeSandbox recreation of the problem I have. 这是我遇到的问题的CodeSandbox重新创建的链接。
https://codesandbox.io/s/playererrordemo-r6bt2 https://codesandbox.io/s/playererrordemo-r6bt2
setInterval
creates a closure over isPlaying
, that's why it's always the same value. setInterval
在isPlaying
之上创建一个闭包,这就是为什么它总是相同的值。
The interval keeps the reference to the value of isPlaying
, it was called with. 时间间隔保留对
isPlaying
的值的引用,它是通过with调用的。 To change that you might need to clearInterval
and start a new one when isPlaying
changes. 要进行更改,您可能需要
clearInterval
并在isPlaying
更改时开始一个新的isPlaying
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.