我是一个初学者,我觉得我在某个地方犯了一个根本性的错误。我正在制作一个简单的 React 组件,以便使用 Tone JS 按顺序播放音符。我无法使用按钮更新笔记。当我单击按钮检查它们是否已更新时,状态似乎已更改,但该repeat
功能仍在播放“旧音符”。我哪里错了?
// create a synth
let synth = new Tone.Synth({
attack: 0.5,
decay: 0.5,
sustain: 1,
release: 5,
volume: -10
}).toDestination()
const Main = () => {
// set state with note values
const [noteValue, setNoteValue] = useState([
{ note: 'C4', properties: ''},
{ note: 'C4', properties: ''}
])
const [isPlaying, setIsPlaying] = useState(false)
// start/stop transport
const startStop = () => {
if (!isPlaying) Tone.start()
setIsPlaying(!isPlaying)
!isPlaying ? Tone.Transport.start() : Tone.Transport.stop()
}
Tone.Transport.bpm.value = 140
// song loop function - always displays the same notes after state change
let index = 0
function repeat(time){
const position = index % noteValue.length
const synthNote = noteValue[position]
console.log(noteValue)
synth.triggerAttackRelease(synthNote.note, time)
index++
}
// set the transport on the first render
useEffect(() => {
Tone.Transport.scheduleRepeat((time) => {
repeat(time)
}, '4n')
},[])
// the "change note values" button doesn't change them inside the repeat function
return <>
<button onClick={() => setNoteValue([
{ note: 'C5', properties: ''},
{ note: 'C5', properties: ''}
])}>Change Note Values</button>
<button onClick={() => console.log(noteValue)}>Check note values</button>
<button onClick={() => startStop()}>Start/Stop</button>
</>
谢谢你。