ESLint:Typescript React 中的“道具验证中缺少 .map”(eslint React/prop-types)

edw*_*mos 4 typescript reactjs eslint

第一次发帖!

我正在使用 Typescript 和 React 来制作一个小项目。我遇到 ESLint 问题,无法识别具有该类型的 prop 变量string[]通常具有 .map 函数,因为它是一个数组。

应用程序.tsx

import React, { useState } from 'react'

function App() {
  const [ingredientsList, setIngredientsList] = useState<string[]>([]);

  return (
    <div className="App">
      <Route path="/" exact render={() => <IngredientListSearch ingredientsList={ingredientsList} setIngredientsList={setIngredientsList} />} />
      <Route path="/about" exact component={About} />
   </div>
  );
}

export default App;
Run Code Online (Sandbox Code Playgroud)

在我的 IngredientListSearch.tsx 中

import React, { useState } from 'react';
// ... bootstrap imports

type Props = {
  ingredientsList: string[]
  setIngredientsList: (arr: string[]) => void
}

function IngredientListSearch({ ingredientsList, setIngredientsList }: Props) {
  // state hooks
  const [searchTerm, setSearchTerm] = useState<string>('');

  // ... miscellaneous logic functions
  
  // function with error in question
  function makeIngredientItems() {
    return (
      <>
        <p>Included Ingredients:</p>
        <ListGroup variant="flush">
          // piece of code in question
          {ingredientsList.map((name, index) => (
            <ListGroup.Item key={index} variant="info">
              // ... Item details here
            </ListGroup.Item>
          ))}
        </ListGroup>
      </>
    );
  }

  return (
    <>
      //... html elements that work fine
      
      <div className="ingredient-list-container">
        {
          ingredientsList.length === 0
            ? <p>Add some Ingredients to get started!</p>
            : makeIngredientItems()
        }
        </div>
        <div />
      </div>
    </>
  );
}

export default IngredientListSearch;
Run Code Online (Sandbox Code Playgroud)

ESLint 会向我抛出一条错误消息'ingredientsList.map' is missing in props validation (eslint react/prop-types)

我不太确定问题是什么,如果我能得到任何帮助,我将不胜感激!

编辑:

IngredientListSearch.propTypes在文件底部添加与我的 Props 一起使用解决了我的 linter 错误,如下所示。

type Props = {
  ingredientsList: string[],
  setIngredientsList: (arr: string[]) => void
}

function IngredientListSearch({ ingredientsList, setIngredientsList }: Props) {
//... component
}

IngredientListSearch.propTypes = {
  ingredientsList: PropTypes.arrayOf(PropTypes.string).isRequired,
  setIngredientsList: PropTypes.func.isRequired,
};
Run Code Online (Sandbox Code Playgroud)

但同时使用 propTypes 和 Typescript 对我来说没有意义。我理解 Typescript 仅在编译时进行类型检查,而 propTypes 在运行时进行检查,但我不认为两者都是必要的。

我的项目使用 Typescript 声明 Prop 类型运行得很好,而这只是 ESlinter 对我大喊大叫。我将删除该react/prop-types规则并继续使用type Props.

Muh*_*ain 5

像这样定义 prop 的类型:

IngredientListSearch.propTypes = {
  ingredientsList: PropTypes.arrayOf(PropTypes.string)
}
Run Code Online (Sandbox Code Playgroud)

props是一个普通的对象。如果您想迭代它,请添加适当的道具类型检查。