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

React点击按钮随机展示state集合中单个条目功能失效问题求助

React运势功能代码问题修复

你代码中存在2处导致功能异常的错误,修改对应位置即可正常运行:

  • 点击事件绑定错误:你在button的onClick属性中写的Fortune.getFortune是尝试调用类的静态方法,而getFortune是绑定在类实例上的方法,需要修改为this.getFortune才能正确触发。
  • 渲染字段取值错误:你在h5标签中渲染的是this.state.fortunes,也就是整个运势数组,会直接输出所有内容,需要修改为this.state.fortune,仅展示随机抽取到的单条运势。

修复后的完整代码

import React from "react";
import {Link} from "react-router-dom"

class Fortune extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fortunes: [
        "An exciting opporunity lies ahead",
        "A long time friend will brirng wise advice in the coming week",
        "You will find great fortunes in unexpected places",
        "Never give up... Unless you want to thats cool too",
        "111",
        "222",
        "333",
        "444",
        "Maybe a nap is what you need",
        "Don't Text Your EX!"
      ],
      fortune: ""
    }
  }

  componentDidMount() {
    this.getFortune();
  }

  getFortune = () =>  {
    let rand = Math.floor(Math.random() * this.state.fortunes.length)
    console.log(rand);
    this.setState({
      fortune: this.state.fortunes[rand]
    })
  }

  render() {
    return (
      <body>
        <div className="home-buttons-wrapper">
          <button onClick={this.getFortune}>Your Fortune</button>
          <h5>{this.state.fortune}</h5>
        </div>
      </body>
    )
  }
}

console.log('getFortune');

export default Fortune;

可选优化

如果你不需要页面加载完成就自动展示第一条运势,可以直接删除componentDidMount生命周期函数内的this.getFortune()调用。


内容的提问来源于stack exchange,提问作者Eddy10

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:54:06