简体   繁体   中英

Line 0: Parsing error: Cannot read property 'map' of undefined TypeScript React

I was replacing an app created using React and JS with TypeScript using ts migrate , but the following error occurred in the file App.tsx .

Line 0: Parsing error: Cannot read property 'map' of undefined

The following is App.tsx

import React, { useState, useEffect, useCallback} from 'react';
import './assets/styles/style.css';
import {AnswersList, Chats} from './components/index';
import FormDialog from './components/Forms/FormDialog';
import {db} from './firebase/index';

const App = () => {
  const [answers, setAnswers] = useState([]);
  const [chats, setChats] = useState([]);
  const [currentId, setCurrentId] = useState("init");
  const [dataset, setDataset] = useState({});
  const [open, setOpen] = useState(false);

  interface Dataset {
    "answers": Array<Answer>,
    "question": string
  }

  interface Answer {
    "answers": [
      {"content": string, "nextId": string}
    ]
  }


  const displayNextQuestion = (nextQuestionId: string, nextDataset: Dataset) => {
    addChats({
      text: nextDataset.question,
      type: 'question'
    })

      setAnswers(nextDataset.answers)
      setCurrentId(nextQuestionId)
  }

  const selectAnswer = (selectedAnswer: any, nextQuestionId: any) => {
    switch(true) {
      case (nextQuestionId === 'contact'):
          handleClickOpen()
          break;

      case (/^https:*/.test(nextQuestionId)):
          const a = document.createElement('a');
          a.href = nextQuestionId;
          a.target = '_blank';
          a.click();
          break;

      default:
          addChats({
              text: selectedAnswer,
              type: 'answer'
          })
        setTimeout(() => displayNextQuestion(nextQuestionId, dataset[nextQuestionId]), 500) 
        break;
    }
  }

  const addChats = (chat: any) => {
    setChats((prevState) => {
      return [...prevChats, chat]
    })
  }

  const handleClickOpen = () => {
    setOpen(true)
  };

  const handleClose = useCallback(() => {
      setOpen(false)
  }, [setOpen]);


  useEffect(() => { 
    (async() => {
      const initDataset = {};

      await db.collection('questions').get().then(snapshots => {
        snapshots.forEach(doc => {
          const id = doc.id
          const data = doc.data()
          initDataset[id] = data
        })
      })

      setDataset(initDataset)
      displayNextQuestion(currentId, initDataset[currentId])
    })()
  }, [])

  useEffect(() => {
      const scrollArea = document.getElementById('scroll-area')
      if (scrollArea) {
        scrollArea.scrollTop = scrollArea.scrollHeight
      } 
  })

  return(
    <section className="c-section"> 
      <div className="c-box">
        <Chats chats={chats} />
        <AnswersList answers={answers} select={selectAnswer} />
        <FormDialog open={open} handleClose={handleClose} />
      </div>
    </section>
  );
}

export default App;

The following is package.json

{
  "name": "chatbot",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.11.2",
    "@material-ui/icons": "^4.11.2",
    "@material-ui/system": "^4.11.2",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "@types/react-router-dom": "^5.1.6",
    "@typescript-eslint/eslint-plugin": "^4.9.0",
    "@typescript-eslint/parser": "^4.9.0",
    "firebase": "^7.24.0",
    "react": "^16.14.0",
    "react-dom": "^16.14.0",
    "react-scripts": "3.4.3"
  },
  "resolutions": {
    "@typescript-eslint/eslint-plugin": "^4.1.1",
    "@typescript-eslint/parser": "^4.1.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {},
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "ts-loader": "^8.0.11",
    "ts-migrate": "^0.1.10",
    "typescript": "^4.1.2"
  }
}

When I was researching the error, I found this page , so I tried it with reference to it, but it didn't change.

By the way, here's what I tried

  • Delete the node_modules file and install npm again
  • Installing @typescript-eslint/eslint-plugin and @typescript-eslint/parser

If you delete the description of the interface Dataset and interface Answer in App.tsx , the relevant error disappears. But another type of error occurs.

I couldn't get a good hint by googling, so I asked this question.

I would appreciate it if you could tell me the cause of this Line 0: Parsing error: Cannot read property 'map' of undefined and more.

You get the error because react-scripts=3.4.3 is not compatible with typescript=^4.1.2 . The relevant issue can be found here: https://github.com/facebook/create-react-app/issues/9515

You can solve this by either

  1. Upgrading to react-scripts to >=4.0 (which adds support for TypeScript 4 ).
  2. Downgrading typescript to <4 .

I was replacing an app created using React and JS with TypeScript using ts migrate , but the following error occurred in the file App.tsx .

Line 0: Parsing error: Cannot read property 'map' of undefined

The following is App.tsx

import React, { useState, useEffect, useCallback} from 'react';
import './assets/styles/style.css';
import {AnswersList, Chats} from './components/index';
import FormDialog from './components/Forms/FormDialog';
import {db} from './firebase/index';

const App = () => {
  const [answers, setAnswers] = useState([]);
  const [chats, setChats] = useState([]);
  const [currentId, setCurrentId] = useState("init");
  const [dataset, setDataset] = useState({});
  const [open, setOpen] = useState(false);

  interface Dataset {
    "answers": Array<Answer>,
    "question": string
  }

  interface Answer {
    "answers": [
      {"content": string, "nextId": string}
    ]
  }


  const displayNextQuestion = (nextQuestionId: string, nextDataset: Dataset) => {
    addChats({
      text: nextDataset.question,
      type: 'question'
    })

      setAnswers(nextDataset.answers)
      setCurrentId(nextQuestionId)
  }

  const selectAnswer = (selectedAnswer: any, nextQuestionId: any) => {
    switch(true) {
      case (nextQuestionId === 'contact'):
          handleClickOpen()
          break;

      case (/^https:*/.test(nextQuestionId)):
          const a = document.createElement('a');
          a.href = nextQuestionId;
          a.target = '_blank';
          a.click();
          break;

      default:
          addChats({
              text: selectedAnswer,
              type: 'answer'
          })
        setTimeout(() => displayNextQuestion(nextQuestionId, dataset[nextQuestionId]), 500) 
        break;
    }
  }

  const addChats = (chat: any) => {
    setChats((prevState) => {
      return [...prevChats, chat]
    })
  }

  const handleClickOpen = () => {
    setOpen(true)
  };

  const handleClose = useCallback(() => {
      setOpen(false)
  }, [setOpen]);


  useEffect(() => { 
    (async() => {
      const initDataset = {};

      await db.collection('questions').get().then(snapshots => {
        snapshots.forEach(doc => {
          const id = doc.id
          const data = doc.data()
          initDataset[id] = data
        })
      })

      setDataset(initDataset)
      displayNextQuestion(currentId, initDataset[currentId])
    })()
  }, [])

  useEffect(() => {
      const scrollArea = document.getElementById('scroll-area')
      if (scrollArea) {
        scrollArea.scrollTop = scrollArea.scrollHeight
      } 
  })

  return(
    <section className="c-section"> 
      <div className="c-box">
        <Chats chats={chats} />
        <AnswersList answers={answers} select={selectAnswer} />
        <FormDialog open={open} handleClose={handleClose} />
      </div>
    </section>
  );
}

export default App;

The following is package.json

{
  "name": "chatbot",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.11.2",
    "@material-ui/icons": "^4.11.2",
    "@material-ui/system": "^4.11.2",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "@types/react-router-dom": "^5.1.6",
    "@typescript-eslint/eslint-plugin": "^4.9.0",
    "@typescript-eslint/parser": "^4.9.0",
    "firebase": "^7.24.0",
    "react": "^16.14.0",
    "react-dom": "^16.14.0",
    "react-scripts": "3.4.3"
  },
  "resolutions": {
    "@typescript-eslint/eslint-plugin": "^4.1.1",
    "@typescript-eslint/parser": "^4.1.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {},
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "ts-loader": "^8.0.11",
    "ts-migrate": "^0.1.10",
    "typescript": "^4.1.2"
  }
}

When I was researching the error, I found this page , so I tried it with reference to it, but it didn't change.

By the way, here's what I tried

  • Delete the node_modules file and install npm again
  • Installing @typescript-eslint/eslint-plugin and @typescript-eslint/parser

If you delete the description of the interface Dataset and interface Answer in App.tsx , the relevant error disappears. But another type of error occurs.

I couldn't get a good hint by googling, so I asked this question.

I would appreciate it if you could tell me the cause of this Line 0: Parsing error: Cannot read property 'map' of undefined and more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM