显示表数据时不断获取“未定义地图”,React 钩子

问题描述

当使用 State 将输入更改为“年份”时,我尝试显示年份,但我遇到了问题。

const handleChange = (e,countMonth,countYear) =>{

      
  if(e.target.value === 'months'){
    setMonths(countMonth)

  } else if( e.target.value === 'year'){
    setMonths(countYear)
  
  }


}

当使用此地图方法单击年份时,我尝试显示不同的数据:

      <tbody>
        {
          months.map(({ date,count },index) => (
          <tr key={index}>
            <td>{date}</td>
            <td>{count}</td>
          </tr>
        ))}
      </tbody>

我不断收到错误 'TypeError: Cannot read property 'map' of undefined'

这是完整的沙箱代码https://codesandbox.io/s/wizardly-clarke-szge3?file=/src/data.js

解决方法

在您的沙盒代码中,我尝试放置控制台日志,发现 countYearundefined,并且设置为 months

理想情况下,您应该在将 countYear 设置为状态 months [else if( e.target.value === 'year' && countYear)] 之前对其进行验证或修复 countYearundefined 的根本原因

const handleChange = (e,countMonth,countYear) =>{
      
  if(e.target.value === 'months'){
    console.log('countMonth ',countMonth)
    setMonths(countMonth)

  } else if( e.target.value === 'year'){
    console.log('countYear ',countYear)
    setMonths(countYear)
  
  }
}