反应不要在循环内创建函数no-loop-func

时间:2018-11-06 16:46:01

标签: javascript reactjs react-native

我的代码运行良好,但是有一个警告,我想消除“不要在循环中创建函数no-loop-func reactjs”

这是我的代码

renderOptions(categoryOptions) {
const renderData = []
let iterator = 0
// const subCategory = this.state.listSubcategorySelected
const { listSubcategory: subCategory = [], listCategory = [] } = this.props.showFilterRightText

for (const category in categoryOptions) {
  const liData = []

  renderData.push(
    <ul key={`ul.${iterator}`} className="filter-box__collection has-title">
      <li
        key={`lii.${iterator}`}
        className="filter-box__collection__title"
        value={iterator}
        onClick={this.showListOption(iterator)}
      >
        <span>{category}</span>
        <i className="material-icons right-align font-size__18px">
          {this.state.listOption[iterator] ? 'add' : 'remove'}
        </i>
      </li>
    </ul>
  )
  const indexCategory = listCategory.indexOf(category)
  categoryOptions[category].forEach((item, index) => {
    let isCkecked = false
    if (indexCategory >= 0) {
      isCkecked = subCategory[indexCategory] && subCategory[indexCategory].indexOf(item) !== -1
    }

    liData.push(
      <li key={`li${iterator}${index}`} className="filter-box__collection__item">
        <input
          id={item}
          type="checkbox"
          className="filled-in radio__is-for-filter"
          checked={isCkecked !== undefined ? isCkecked : false}
          onChange={this.handleChangeChk(category, item)}
        />
        <label htmlFor={item}>{item}</label>
      </li>
    )
  })
  renderData.push(
    <ul
      key={`ull${iterator}`}
      className="filter-box__collection"
      style={{ display: this.state.listOption[iterator] ? 'none' : 'block' }}
    >
      {liData}
    </ul>
  )

  iterator += 1
}

return renderData

}

控制台告诉我问题出在我发布的代码的第24行

const indexCategory = listCategory.indexOf(category)
      categoryOptions[category].forEach((item, index) => {

任何可能对我有帮助的提示都将非常重要

1 个答案:

答案 0 :(得分:2)

循环是for..of循环,而react函数抱怨的是传递给forEach箭头函数(item, index) =>的那个。这可能比常规的for循环要慢一些,因为JS引擎必须在每次外部迭代时创建一个新的函数上下文,但是它只会慢一些,因此您可以放心地忽略警告。或者您使用常规的for循环:

  for(const [item, index] of categoryOptions[category].entries()) {
   //...
 }