【发布时间】:2021-05-17 03:14:50
【问题描述】:
我必须将笔记与麦克风检测到的传入笔记相匹配。我正在使用 fft 来检测音高并将其与下一个最接近的音符相匹配。它以大约 10x/s 的速度触发 handleNoteEvent。问题是因为 setNote 多次异步 if 语句 == true ,直到 setState 完成设置随后导致应用程序多次重新呈现的值。在使用 React 钩子时如何等到 setState 完成? (currentNote 被多个孩子使用)
编辑:如果我正确理解文档,带有钩子的setState 似乎不会返回承诺或接受回调
编辑 2:我想我必须澄清我的问题:我需要在 if 变为 true 后忽略传入的事件,直到 setState 完成将 currentNote 设置为新的 note 对象。
function App() {
const [currentNote, setNote] = useState(new Note());
//Event handler that gets the event from the fft tuner multiple times a second
const handleNoteEvent = (fftNote) => {
if (currentNote == fftNote)) {
console.log('match');
nextNote();
}
//The problem here is the nextNote() is fired multiple times since setNote is async. How can I ignore all incoming events while setNote is not finished?
const nextNote = () => {setNote(new Note())};
...
}
【问题讨论】:
-
这不适用于功能组件。功能组件中的 setState 不接受第二个参数。
-
setNote是如何变成异步的? AFAIK,setNote是同步的,因为它是 React useState hook。 -
嗯,当前音符的值仅在大约 500 毫秒后才改变,这就是为什么我认为它是异步的
-
是不是因为
Note构造函数很贵?
标签: javascript reactjs react-native