【问题标题】:Keep getting 'map of undefined' when displaying table data, React hooks显示表数据时不断获取“未定义的地图”,React 挂钩
【发布时间】:2021-04-21 05:07:42
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • 这里是你调用handleChange的方式,它需要3个参数~onChange={(e) =&gt; {handleChange(e)}}。看到问题了吗?
  • 您的 handleChange 处理程序需要 3 个参数,但您只传递第一个。 countMonthcountYear 不在我所知的范围内。
  • 是的,我尝试将这两个添加为参数,但仍然不起作用

标签: javascript reactjs nivo-react


【解决方案1】:

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

理想情况下,您应该在将countYear 设置为状态months [else if( e.target.value === 'year' &amp;&amp; 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)
  
  }
}

【讨论】:

  • 回答的目的不是帮助“解决为什么countYearundefined 的根本原因”而不是仅仅指出代码不起作用吗?这是一个有用的答案吗?
  • 你能把它放到沙箱里吗?
猜你喜欢
  • 2020-06-20
  • 1970-01-01
  • 2021-12-27
  • 2020-04-21
  • 2016-08-23
  • 2020-05-17
  • 1970-01-01
  • 1970-01-01
  • 2023-01-21
相关资源
最近更新 更多