You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React.js中BPM计算方法无法返回值但弹窗可显示值的问题求助

Fixing Your React BPM Display Issue

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.state is the object containing the bpm key):
    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 fetch chain 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., isCalculatingBpm in your state) to show a spinner or placeholder while the BPM is being computed, instead of leaving users staring at the initial 3.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:16:55