gpt4 book ai didi

reactjs - ESLint:Typescript React 中的 '.map is missing in props validation'(eslint react/prop-types)

转载 作者:行者123 更新时间:2023-12-05 02:06:00 28 4
gpt4 key购买 nike

第一次发帖!

我正在使用 Typescript 和 React 制作一个小项目。我遇到了一个问题,ESLint 无法识别 string[] 类型的 prop 变量通常会有一个 .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;

在我的 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

最佳答案

像这样定义 Prop 类型:

IngredientListSearch.propTypes = {
ingredientsList: PropTypes.arrayOf(PropTypes.string)
}

props 是一个普通对象。如果您想对其进行迭代,请添加适当的 prop-type 检查。

关于reactjs - ESLint:Typescript React 中的 '.map is missing in props validation'(eslint react/prop-types),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63037619/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com