[英]React parent method passed in child component has stale state
在我的 App.js 中,我有以下内容:
const(sound,SetSound) = useState('beep');
function playSound() {
console.log(sound); // displays beep if called from childComponent and 'honk' if called from App.js
}
return (
<Childcomponent
sound={sound}
setSound={setSound}
playSound={playSound}
/>
...
在我的 ChildComponent 中,我执行以下操作:
props.setSound('honk');
//Later by button click:
props.playSound();
它没有鸣喇叭,而是发出哔哔声。 我错过了什么?
在 app.js 中,我捕捉到按键“a”来调用 playSound()。 当我这样做时,它会在 childComponent 更新后鸣喇叭。 不知何故 props.playSound() 已经过时了。 如果我在 childComponent 中显示 {sound},它会显示更新的“喇叭”。
我试过“绑定”
playSound={() => playSound()} 但它仍然发出哔哔声而不是鸣喇叭。
我如何从 ChildComponent 鸣喇叭?
你的playSound()
函数是什么样的? 似乎playSound()
仍在使用旧的sound
状态。
在 App.js 中,我会将值传递给playSound
函数,以便它使用正确的更新值sound
:
function playSound(sound) {
// Plays the sound with the argument passed in.
}
一旦您使用值'honk'
honk' 调用setSound
,它将无法在同一个 tick 中用于playSound
。 您必须等待下一个渲染周期,然后调用props.playSound()
或者你可以做这样的事情
// This will ensure that playSound is called after setting the state
props.setSound('honk', () => props.playSound());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.