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

React表单表格优化:解决表头重复、姓名排序及本地存储问题

React表单表格系统问题解决方案

1. 解决表头重复渲染问题

问题原因:原代码中把整个<table>标签放在了tables.map()循环内部,导致每条数据生成一个独立表格,表头随数据行重复渲染。

修改方案:将<table>标签移出循环,仅在<tbody>内部循环渲染数据行,<thead>部分只渲染一次。

修改后的TableList.jsx:

import React, { useContext, useState } from 'react'
import { TableContext } from '../../../Context/TableContext'
import { Link } from 'react-router-dom'

const TableList = () => {
  const { tables, deleteTable } = useContext(TableContext)
  const [sortDirection, setSortDirection] = useState(null) // asc/desc/null

  // 排序逻辑
  const sortedTables = [...tables].sort((a, b) => {
    if (!sortDirection) return 0
    const nameA = a.name.toLowerCase()
    const nameB = b.name.toLowerCase()
    return sortDirection === 'asc' ? nameA.localeCompare(nameB) : nameB.localeCompare(nameA)
  })

  const toggleSort = () => {
    setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc')
  }

  return (
    <div>
      {tables.length > 0 ? (
        <table width="100%" border="1" cellspacing="0" cellpadding="0">
          <thead>
            <tr>
              <th rowspan="2" onClick={toggleSort} style={{cursor: 'pointer'}}>
                Name {sortDirection === 'asc' ? '↑' : sortDirection === 'desc' ? '↓' : ''}
              </th>
              <th rowspan="2">Email</th>
              <th rowspan="2">Phone Number</th>
              <th rowspan="2">Date Of Birth</th>
              <th colspan="4">Address</th>
            </tr>
            <tr>
              <th>City</th>
              <th>District</th>
              <th>Province</th>
              <th>Country</th>
            </tr>
          </thead>
          <tbody>
            {sortedTables.map((tablee) => (
              <tr key={tablee.id}>
                <td>{tablee.name}</td>
                <td>{tablee.email}</td>
                <td>{tablee.phoneNumber}</td>
                <td>{tablee.dob}</td>
                <td>{tablee.city}</td>
                <td>{tablee.district}</td>
                <td>{tablee.province}</td>
                <td>{tablee.country}</td>
                <td>
                  <Link to={`/edit/${tablee.id}`}>Edit</Link>
                </td>
                <td>
                  <button onClick={() => deleteTable(tablee.id)}>Delete</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      ) : (
        <p>It seems like no data is entered.</p>
      )}
      <Link to="profile">Profiles</Link>
    </div>
  )
}

export default TableList

2. 实现姓名列字母排序功能

实现逻辑:

  • 添加sortDirection状态控制排序方向(升序/降序/未排序)
  • 点击Name表头切换排序方向
  • 使用数组sort()结合localeCompare()对姓名进行大小写不敏感的字母排序

上述修改后的TableList.jsx已包含排序功能:

  • 点击Name表头可触发排序,显示↑/↓标识当前排序方向
  • 排序基于姓名的小写形式,避免大小写影响排序结果

3. 实现表格数据localStorage持久化

实现逻辑:

  • 从localStorage读取初始数据,作为状态的初始值
  • 监听表格数据变化,实时将数据保存到localStorage

修改后的TableContext.jsx:

import React, { createContext, useReducer, useEffect } from 'react'
import TableReducers from '../Reducers/TableReducers'
import { CREATE_TABLE, EDIT_TABLE, DELETE_TABLE } from '../Reducers/ReducerTypes'

// 从localStorage读取初始数据,无数据则返回空数组
const getInitialState = () => {
  const savedTables = localStorage.getItem('tables')
  return savedTables ? JSON.parse(savedTables) : []
}

const initialState = {
  tables: getInitialState(),
};

export const TableContext = createContext(initialState)

const TableProvider = ({ children }) => {
  const [state, dispatch] = useReducer(TableReducers, initialState);

  const createTable = (tablee) => {
    dispatch({
      type: CREATE_TABLE,
      payload: tablee,
    });
  };

  const editTable = (tablee) => {
    dispatch({
      type: EDIT_TABLE,
      payload: tablee,
    });
  };

  const deleteTable = (id) => {
    dispatch({
      type: DELETE_TABLE,
      payload: id,
    });
  };

  // 监听表格数据变化,实时保存到localStorage
  useEffect(() => {
    localStorage.setItem('tables', JSON.stringify(state.tables))
  }, [state.tables])

  return (
    <TableContext.Provider
      value={{
        tables: state.tables,
        createTable,
        editTable,
        deleteTable,
      }}
    >
      {children}
    </TableContext.Provider>
  );
};

export default TableProvider;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:25:21