第一次发帖!
我正在使用TypeScript和React制作一个小项目。我遇到了一个问题,ESLint没有识别一个类型为string[]
的prop变量通常会有一个.map函数,因为它是一个数组。
App.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'在属性验证中缺失(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
。
eslint-plugin-react
存储库提交问题。看起来像是一个 bug。 - Santiago V.