![](/img/trans.png)
[英]Eslint - 'match' is missing in props validation (react/prop-types)
[英]ESLint: '.map is missing in props validation' (eslint react/prop-types) in Typescript React
第一次发帖!
我正在使用 Typescript 和 React 来制作一个小项目。 我遇到了 ESLint 的问题,它无法识别类型为string[]
的 prop 变量通常具有 a.map function 因为它是一个数组。
应用程序.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;
在我的 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;
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,
};
但是对我来说同时使用 propTypes 和 Typescript 没有意义。 我了解 Typescript 仅在编译时进行类型检查,而 propTypes 在运行时检查,但我认为两者都不是必需的。
我的项目工作得很好,用 Typescript 声明了一个 Prop 类型,它只是 ESlinter 对我大喊大叫。 我将删除react/prop-types
规则并继续使用type Props
。
像这样定义道具的类型:
IngredientListSearch.propTypes = {
ingredientsList: PropTypes.arrayOf(PropTypes.string)
}
props
是一个普通的 object。 如果您想对其进行迭代,请添加适当的道具类型检查。
在 your.eslintrc 或.eslintrc.js 中,在规则部分添加下一行(在我的例子中是.eslintrc):
"rules": {
// other rules
"react/prop-types" : "off",
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.