reactjs 找不到名称且隐含具有任何类型时出错

flseospp  于 2023-02-22  发布在  React
关注(0)|答案(2)|浏览(199)

出现以下错误:

ERROR in src/components/Tasks.tsx:6:2

TS2552: Cannot find name 'Task'. Did you mean 'Tasks'?
    4 | return(
    5 |         <>
  > 6 | {Task.map((task) => (
      |  ^^^^
    7 | <h3 key={task.id}>{task.text}</h3>
    8 | )) }
    9 |
ERROR in src/components/Tasks.tsx:6:12

TS7006: Parameter 'task' implicitly has an 'any' type.
    4 | return(
    5 |         <>
  > 6 | {Task.map((task) => (
      |            ^^^^
    7 | <h3 key={task.id}>{task.text}</h3>
    8 | )) }
    9 |

任务. tsx代码:

import PropTypes from 'prop-types'

const Tasks = () => {
return(
        <>
{Task.map((task) => (
<h3 key={task.id}>{task.text}</h3>
)) }

        </>
    )
}

export default Tasks
btxsgosb

btxsgosb1#

由于TypeScript编译器无法推断map函数中task参数的类型,因此导致错误。可以通过使用接口或类型显式定义task的类型来修复此问题。

import PropTypes from 'prop-types';

interface Task {
  id: number;
  text: string;
}

const tasks: Task[] = [
  { id: 1, text: 'Task 1' },
  { id: 2, text: 'Task 2' },
];

const Tasks = () => {
  return (
    <>
      {tasks.map((task: Task) => (
        <h3 key={task.id}>{task.text}</h3>
      ))}
    </>
  );
};

export default Tasks;

此外,定义或导入Task变量,并确保它是具有属性idtext的对象数组。

kq0g1dla

kq0g1dla2#

谢谢您的回答,在App.tsx中定义如下:

import { useState } from 'react'
import Header from './components/Header'
import Tasks from './components/Tasks'

const App = () => {
  const [tasks, setTasks] = useState([
            {
        id: 1,
        text: 'Audit mit Lieferanten Schäffler durchführen',
        day: 'Feb 28th at 2:30 pm',
        reminder: true,
        },
        {
        id: 2,
        text: 'Eskalation bei der Firma Balluff',
        day: 'Feb 6th at 1:30 pm',
        reminder: true,
        },
        {
        id: 3,
        text: 'Lieferantengespräch mit ADE durchführen',
        day: 'Feb 5th at 2:30 pm',
        reminder: false,
        },
])

  return (
    <div className='container'>
      <Header />
      <Tasks />
    </div>
  )
}

export default App;

相关问题