reactjs - 第 0 行 : Parsing error: Cannot read property 'map' of undefined"- TypeScript Custom Hook

标签 reactjs typescript react-hooks parsing-error

我收到错误“./src/hooks/usePagination.tsx 第 0 行:解析错误:无法读取未定义的属性“map””您知道原因是什么吗?我花了半个晚上在 stackoferflow 等上寻找答案,并多次尝试修复该问题,但均未成功。

首先我考虑了我的数据格式,因为现在是

[
    {"id":1,"firstName":"Cori","lastName":"Wescott","email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6c5d1c3d5c5c9d2d296e6c3d2d5df88c5c9cb" rel="noreferrer noopener nofollow">[email protected]</a>","gender":"Male","ip_address":"236.58.118.85"},
    {"id":2,"firstName":"Teena","lastName":"Kedge","email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="35415e50515250047554585057595a1b5f45" rel="noreferrer noopener nofollow">[email protected]</a>","gender":"Female","ip_address":"74.32.179.20"},
    {"id":3,"firstName":"Englebert","lastName":"Menlove","email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="442129212a282b322176042729316a212031" rel="noreferrer noopener nofollow">[email protected]</a>","gender":"Male","ip_address":"91.249.51.126"},
]

我更改了数据而不是json,但这没有帮助。后来我寻找了错误的标记、字母、字符等等——没有结果。最后,我的研究促使我阅读有关 npm 或其他软件包版本太旧的信息。呃,我现在放弃了..

也许有人会发现问题。

function App() {
  const [paginationState, paginationActions] = usePagination(dataEntries, 2);
  return (
    <div className="App">
      <h2>Users</h2>
      { !paginationState.isBusy && <PaginatedTable dataEntries={paginationState.entries}/> }
      <Pagination state={paginationState} actions={paginationActions}/>
    </div>
  );
}

export default App;
d.ts file

export interface User {
  id: number
  firstName: string
  lastName: string
}

export interface PaginationState<T> {
  lastPageIdx: number
  actualPageIdx: number
  entries: T[]
  isBusy: boolean
}

export interface PaginationActions {
  goToFirstPage: () => void
  goToPrevPage: () => void
  goToNextPage: () => void
  goToLastPage: () => void
  goToPage: (number: number) => void
}

自定义 Hook

function usePagination<T>(dataEntries: T[], elementsOnPage: number): [PaginationState<T>, PaginationActions] {
  const [actualPageIdx, setActualPageIdx] = useState(1)
  const lastPageIdx = Math.ceil(dataEntries.length / elementsOnPage)
  const [isBusy, setIsBusy] = useState(false)

  useEffect(() => {
    setIsBusy(true)
    let timer = setTimeout(() => {
      setIsBusy(false)
      clearTimeout(timer)
    }, 333)

    return () => {
      clearTimeout(timer)
    }
  }, [actualPageIdx])

  const entriesOnSelectedPage = () => {
    const firstEntry = (actualPageIdx - 1) * elementsOnPage
    const lastEntry = firstEntry + elementsOnPage
    return dataEntries.slice(firstEntry, lastEntry)
  }

  const entries = entriesOnSelectedPage()

  const goToFirstPage = () => {
    setActualPageIdx(1)
  }

  const goToLastPage = () => {
    setActualPageIdx(lastPageIdx)
  }

  const goToPage = (page: number) => {
    setActualPageIdx(page)
  }

  const goToPrevPage = () => {
    setActualPageIdx((actualPageIdx) => (actualPageIdx === 1 ? actualPageIdx : actualPageIdx - 1))
  }

  const goToNextPage = () => {
    setActualPageIdx((actualPageIdx) =>
      actualPageIdx === lastPageIdx ? actualPageIdx : actualPageIdx + 1
    )
  }
  
  return [
    { 
      actualPageIdx, 
      lastPageIdx, 
      entries, 
      isBusy 
    },
    {
      goToFirstPage,
      goToPrevPage,
      goToPage,
      goToNextPage,
      goToLastPage,
    },
  ] 
}

分页

interface PaginationProps {
  state: PaginationState<User>
  actions: PaginationActions
}

const Pagination: FC<PaginationProps> = ({ state, actions }) => {
  const pageNumbers = []

  for (let i = 1; i <= state.lastPageIdx; i++) {
    pageNumbers.push(i)
  }

  const renderPagination = pageNumbers.map((number) => (
    <button
      key={number}
      onClick={() => actions.goToPage(number)}
      className={
        state.actualPageIdx === number ? styles.actualIdxStyle : styles.paginationStyle
      }
    >
      {number}
    </button>
  ))

  return (
    <div className={styles.paginationContainer}>
      <button onClick={actions.goToFirstPage}>GO TO FIRST</button>
      <button onClick={actions.goToPrevPage} data-testid="goToPrevPage">
        <i className="fas fa-chevron-left"></i>
      </button>
      <div data-testid="goToPageButtons">{renderPagination}</div>
      <button onClick={actions.goToNextPage} data-testid="goToNextPage">
        <i className="fas fa-chevron-right"></i>
      </button>
      <button onClick={actions.goToLastPage}>GO TO LAST</button>
    </div>
  )
}

分页表

interface PaginatedTableProps {
  dataEntries: User[]
}

const PaginatedTable: FC<PaginatedTableProps> = ({ dataEntries }) => {
  const tableEntry = dataEntries && dataEntries.map(({ id, firstName, lastName }) => (
    <div key={id} className={styles.tableStyle}>
      <p>
        {id}{'. '}
      </p>
      <p>
        {firstName} {lastName}
      </p>
    </div>
  ))
  return (
    <div>
      <div className={`${styles.tableStyle} ${styles.headStyle}`}>
        <p>No.</p>
        <p>Name</p>
      </div>
      <div data-testid="users">{tableEntry}</div>
    </div>
  )
}

最佳答案

可以确认@radicand 在上面的评论中提到的内容。 以下软件包需要降级到这些版本:

"@typescript-eslint/eslint-plugin": "3.9.1",
"@typescript-eslint/parser": "3.9.1",
"typescript": "3.9.2"

Typescript 4.x 和 eslint 4.x 软件包无法与 3.4.3 版本的 react 脚本一起使用。

关于reactjs - 第 0 行 : Parsing error: Cannot read property 'map' of undefined"- TypeScript Custom Hook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63693429/

相关文章:

reactjs - react-hook-form - 无法将表单数据传递给父组件

reactjs - React.js useEffect 和依赖数组,使用解构 useState

javascript - 导入默认导出和命名导出是否会加载模块两次?

javascript - 根据父级的 prop 更改响应子级状态更新

javascript - 为什么在 .vue 中声明的基于 ts 类的 vue 组件的静态方法只能在 .vue 的脚本 block 中工作?

reactjs - 何时使用原生 React.useReducer Hook 以及它与 Redux 的区别

php - Next js - 每次更改路由时在服务器端调用一个函数

javascript - 如何解决以下 es-lint warnings-Warning as '' Expected to return a value”?

angular - 在 Stackblitz Angular 项目中使用 Object.values()

angular - 我的模板引用变量 .nativeElement 未定义