【问题标题】:ReactJS - Can not map whilst using onChange eventReactJS - 使用 onChange 事件时无法映射
【发布时间】:2018-04-21 12:04:13
【问题描述】:

我有 category select 下拉菜单,此时,我正在使用带有数组的虚拟数据。

constructor() {
    super();
    this.state = {
        search: '',
        categories: '',
        products: '',
        categories: ['Technology', 'Sport', 'Fashion', 'Clothes'],
    }

然后,我使用映射来遍历它

 <div className="col-lg-4">
    <select id="categories" className="form-control">
      {
       this.state.categories.map((i, index) => <option key={index} value={i} >{i}</option>)
      }
    </select>
 </div>

这样就可以了。但是,我想根据所选类别更改状态,但是当我将 onChange={handleCategories} 添加到 select 时出现错误:

Uncaught TypeError: this.state.categories.map is not a function

通过谷歌搜索,我注意到人们在尝试对对象使用映射时通常会遇到问题(仅适用于数组),但是我找不到任何指向我的问题的链接。

不工作:

<div className="col-lg-4">
   <select id="categories"  onChange={handleCategories}  className="form-control">
      {
        this.state.categories.map((i, index) => <option key={index}  >{i}</option>)
      }
   </select>
</div>

【问题讨论】:

  • 用无效的代码更新问题。你是如何传递onChange 函数的?
  • @Prakash 更新
  • 更改选项时是否出现错误?如果是,则显示handleCategories 函数。
  • 我是几分钟前才知道的,是方法的问题,我什至以为我不明白为什么,但是是的,你是对的。

标签: reactjs mapping onchange


【解决方案1】:

你需要使用this.handleCategories.bind(this)将函数绑定到实例上,否则函数不会知道state.categories

【讨论】:

  • 我像这样绑定了this.handleCategories = this.handleCategories.bind(this),但无论如何我找到了错误来自的确切位置,这是在方法中。
  • @Seinfeld 你是说你已经解决了问题?
  • 是的,我只是忘记使用target.value
猜你喜欢
  • 1970-01-01
  • 2019-02-28
  • 2016-01-20
  • 2018-03-31
  • 2016-08-05
  • 2018-04-25
  • 1970-01-01
  • 2017-05-02
  • 2015-01-21
相关资源
最近更新 更多