sách gpt4 ai đã đi

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

In lại 作者:行者123 更新时间:2023-12-05 02:06:00 29 4
mua khóa gpt4 Nike

第一次发帖!

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

应用.tsx

import React, { useState } from 'react'

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

trở lại (

} />


);
}

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('');

// ... miscellaneous logic functions

// function with error in question
function makeIngredientItems() {
trở lại (
<>

Included Ingredients:



// piece of code in question
{ingredientsList.map((name, index) => (

// ... Item details here

))}


);
}

trở lại (
<>
//... html elements that work fine


{
ingredientsList.length === 0
?

Add some Ingredients to get started!


: makeIngredientItems()
}




);
}

export default IngredientListSearch;

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

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

biên tập:

Sẽ 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.

1 Câu trả lời

像这样定义 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/

29 4 0
Bài viết được đề xuất: Python sqlite3 在本地成功,但在 Github Action 上失败
Bài viết được đề xuất: c++ - 如何在 VS2019 CUDA 项目中启用 C++17 代码生成
Bài viết được đề xuất: python - fig, ax = plt.subplots() 意思
Bài viết được đề xuất: docker - ssh-keygen : command not found in Docker
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com