[英]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.