在 React 中渲染列表并出现 Eslint 错误 "no unused expressions"

Rendering a list in React and get Eslint error "no unused expressions"

我正在重新学习 eslint 并正在为创建 React 应用程序进行测试配置,还包括用于格式化的 prettier。错误状态编译失败:'Expected an assignment or function call and instead saw an expression no-unused-expressions'。我去了 eslint 文档 https://eslint.org/docs/rules/no-unused-expressions 并将 'allows' 添加到规则部分。我该如何解决这个问题,这可能是与 eslint 的格式冲突吗?

错误指向列表项开始的行。

<div>
    <ul>
      {this.state.list.map((item, index) => {
        <li key={index}>
          {item}
          <button
            type="button"
            onClick={() => {
              this.onRemoveItem(index);
            }}>
            Remove
          </button>
        </li>;
      })}
    </ul>
  </div>

这是我的。eslintrc.json

{
  "extends": ["prettier", "prettier/react"],
  "plugins": ["react", "jsx-a11y", "import", "prettier"],
  "rules": {
    "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
    "prettier/prettier": "error",
    "arrow-body-style": ["warn", "always"],
    "allowShortCircuit": true,
    "allowTernary": true
  },
  "parser": "babel-eslint",
  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true,
      "modules": true
    }
  },

  "env": {
    "browser": true,
    "node": true,
    "es6": true,
    "node": true
  }
}

Return 值未使用,因此引发错误:

<div>
    <ul>
      {this.state.list.map((item, index) => {
        return (
         <li key={index}>
          {item}
          <button
            type="button"
            onClick={() => {
              this.onRemoveItem(index);
            }}>
            Remove
          </button>
        </li>
       );
      })}
    </ul>
  </div>

您也可以使用括号 return 对象:

<div>
    <ul>
      {this.state.list.map((item, index) => (
         <li key={index}>
          ...
        </li>
      ))}
    </ul>
  </div>

或者,即使您在同一行中开始 <li>,您也可以避免:

{this.state.list.map((item, index) => <li key={index}>
   ...
  </li>
)}