![](/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.