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

React.js中如何给学生数组ID绑定布尔值并点击按钮切换对应布尔状态

React实现方案

核心逻辑说明

  • 组件挂载后启动30秒间隔的API轮询,卸载时自动清除定时器避免内存泄漏
  • 每次接口返回数据时,优先保留本地已修改的isClicked状态,新增学生自动使用默认false值
  • 点击删除按钮仅修改对应学生的isClicked状态,不影响其他数据
  • 页面刷新后组件重新初始化,所有学生默认恢复isClicked=false状态,符合需求

完整可运行代码

import React, { Component } from 'react';

class Table extends Component {
  constructor(){
    super();     
    this.state = {
      students: [] // 存储学生列表数据
    };
    this.deleteRecord = this.deleteRecord.bind(this);
    this.timer = null; // 存储轮询定时器
  } 

  componentDidMount() {
    // 组件挂载后先请求一次数据,再启动30秒轮询
    this.fetchStudents();
    this.timer = setInterval(() => {
      this.fetchStudents();
    }, 30 * 1000);
  }

  componentWillUnmount() {
    // 组件卸载清除定时器
    clearInterval(this.timer);
  }

  // 请求学生数据接口
  fetchStudents() {
    // 此处替换为你的实际接口地址,可改用axios等请求库
    fetch('你的API接口地址')
      .then(res => res.json())
      .then(newStudents => {
        // 用Map存储已有学生数据,保留已经修改的isClicked状态
        const oldStudentMap = new Map(
          this.state.students.map(item => [item.id, item])
        );
        // 合并新旧数据:旧数据保留状态,新数据用默认返回的isClicked=false
        const mergedStudents = newStudents.map(item => {
          return oldStudentMap.get(item.id) || item;
        });
        this.setState({
          students: mergedStudents
        });
      })
      .catch(err => console.error('接口请求失败', err));
  }

  // 点击删除按钮修改对应学生状态
  deleteRecord(std_id) {
    const updatedStudents = this.state.students.map(item => {
      if (item.id === std_id) {
        return {...item, isClicked: true};
      }
      return item;
    });
    this.setState({
      students: updatedStudents
    });
  }
  
  render() { 
    return (
      <table border={1} cellPadding={8}>
        <thead>
          <tr>
            <th>学生ID</th>
            <th>学生姓名</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {
            this.state.students.map(student => {
              // 可根据需求调整isClicked=true的展示逻辑,比如隐藏、置灰等
              if (student.isClicked) return null;
              return (
                <tr key={student.id}>
                  <td>{student.id}</td>
                  <td>{student.name}</td>
                  <td>
                    <button onClick={() => this.deleteRecord(student.id)}>
                      删除
                    </button>
                  </td>
                </tr> 
              )
            })
          }
        </tbody>
      </table>
    )
  }
}

export default Table;

关键调整说明

  • 原代码缺少轮询逻辑,新增了componentDidMount和componentWillUnmount的定时器管理
  • 新增了新旧数据合并逻辑,不会因为接口刷新重置已经点击的删除状态
  • 修正了原代码render无返回值、onclick小写错误、方法绑定名称错误等问题
  • 内置了isClicked=true时隐藏行的逻辑,可根据业务需求自行修改为置灰、添加删除标记等效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:42:01