React.js中BPM计算方法无法返回值但弹窗可显示值的问题求助
Hey there, let's figure out why your calculated BPM isn't showing up in your component's render output—great job narrowing down that the alert works, so we know the BPM calculation itself is solid!
The Root Cause
Looking at your render method, there's a critical mistake in how you're accessing the bpm state:
var { bpm } = this.state.bpm;
this.state.bpm is a primitive number (your initial value is 3, later updated to the calculated BPM). You're trying to use object destructuring on a number, which doesn't work—this line ends up setting bpm to undefined because numbers don't have a bpm property to extract.
Quick Fix
Change that line to either:
- Directly access the state property (simple and clear):
const bpm = this.state.bpm; - Or properly destructure from the state object (since
this.stateis the object containing thebpmkey):const { bpm } = this.state;
Additional Robustness Tips
Since your bpmCalculator is asynchronous (relies on fetch and promises), here are a couple of extra tweaks to polish this up:
- Add network error handling to your
fetchchain to catch failed requests:fetch(src) .then(response => { if (!response.ok) throw new Error('Failed to load audio file'); return response.arrayBuffer(); }) // ... rest of your promise chain - Consider adding a loading state (e.g.,
isCalculatingBpmin your state) to show a spinner or placeholder while the BPM is being computed, instead of leaving users staring at the initial3.
Corrected Render Snippet
Here's how your fixed render method should look:
render() { const { bpm } = this.state; // Fixed line let playBtn = '\u25BA'; if (this.state.isPlay) { playBtn = '\u258C\u258C'; } return ( <div className="player"> <audio id={"currentAudio" + this.props.songs.id} src={"/audio/" + this.props.songs.source}/> <span className="orange-button" onClick={() => { this.toggleSong(this.props.songs.id) }}> {playBtn} </span> <div className="track-info"> <h2 className="track-title">{this.props.songs.title}</h2> <h3 className="track-user">{this.props.songs.artist}</h3> <h3><span>{bpm}</span></h3> </div> </div> ); }
Once you apply this fix, your component will correctly display the calculated BPM once the asynchronous process finishes!
内容的提问来源于stack exchange,提问作者Liad Levy

