ReactJS表格中添加多日期并展示每月指定日期的问题求助
React表格展示每月指定日期问题解决方案
现有代码问题梳理
- 语法错误:
useState不能写在普通函数calculate内部,React Hook只能在组件顶层或自定义Hook中调用 - 日期计算逻辑错误:直接将字符串拼接后加
30,不会得到30天后的日期,只会得到字符串末尾追加"30"的错误结果 - 标签嵌套错误:JSX里
tbody结束位置错误写成了</thead>,且缺少<table>标签包裹表头和表体 - 变量未定义:代码中
setM、date1、date2、principal等变量没有声明逻辑 - 冗余代码:重复手写多个
tr标签,维护成本高
正确实现代码
import { useState, useEffect } from 'react' const DepositTable = () => { // 可自定义本金、年利率等参数 const principal = 10000 const yearRate = 0.03 // 存储每月的日期、利息、累计利息数组 const [monthList, setMonthList] = useState([]) // 计算n个月后的对应日期 const getMonthDate = (baseDate, addMonthCount) => { const targetDate = new Date(baseDate) targetDate.setMonth(baseDate.getMonth() + addMonthCount) // 格式化日期为YYYY-MM-DD,自动补前导零 const year = targetDate.getFullYear() const month = String(targetDate.getMonth() + 1).padStart(2, '0') const day = String(targetDate.getDate()).padStart(2, '0') return `${year}-${month}-${day}` } useEffect(() => { const now = new Date() // 调整length的值即可修改展示的月份数量 const list = Array.from({length: 3}, (_, index) => { const currentDate = getMonthDate(now, index) // 单月利息可替换为自定义计算逻辑 const monthInterest = principal * yearRate / 12 const totalInterest = monthInterest * (index + 1) return { index: index + 1, date: currentDate, interest: monthInterest.toFixed(2), totalInterest: totalInterest.toFixed(2) } }) setMonthList(list) }, []) return ( <div> <table> <thead> <tr> <th>#</th> <th>Deposit Amount</th> <th>Interest</th> <th>Date</th> <th>Total Interest</th> </tr> </thead> <tbody> {monthList.map(item => ( <tr key={item.index}> <td>{item.index}</td> <td>{principal}</td> <td>{item.interest}</td> <td>{item.date}</td> <td>{item.totalInterest}</td> </tr> ))} </tbody> </table> </div> ) } export default DepositTable
实现说明
- 用数组遍历渲染表格行,无需重复编写重复结构,后期调整展示月份数量只需修改生成数组的长度参数
- 调用
Date.setMonth计算每月对应日期,自动处理跨月、跨年、不同月份天数差异的场景,比手动加30天更符合「每月指定日期」的需求 - 用
padStart补全日期前导零,统一日期格式为YYYY-MM-DD - 所有Hook均放在组件顶层调用,符合React语法规范
内容的提问来源于stack exchange,提问作者Shahnawaz Ayon
相关产品推荐
相关产品推荐

