【问题标题】:error when trying to fetch data from server Parsing error: Unexpected token尝试从服务器获取数据时出错解析错误:意外的令牌
【发布时间】:2020-09-01 20:20:09
【问题描述】:

我正在使用 pern 堆栈,当我尝试使用 useEffect 或 useState 时,我收到此错误。 所以,我使用 postgres 创建数据库并使用 express 使用 pool 连接

创建了一个端点并尝试在我的代码中获取它

import React, {useEffect , useState} from 'react';
import Table  from './Table';
import Nav from './Navi';
import TemplateList from './TemplateList';
import {Tab,Tabs} from 'react-bootstrap';
class Dashboard extends React.Component{
  const [tdata,setTdata] = React.useState([]);

  info = async () => {
    try {
      const response = await fetch("http://localhost:8080/dashboard");
      const dataServer = await response.json();
      React.setTdata(dataServer);
    } catch (err) {
      console.error(err.message);
    }
  }
  console.log(tdata);

  React.useEffect(() => {
    info();
  }, []);

错误

Failed to compile
./src/components/Dashboard.js
  Line 7:9:  Parsing error: Unexpected token

   5 | import {Tab,Tabs} from 'react-bootstrap';
   6 | class Dashboard extends React.Component{
>  7 |   const [tdata,setTdata] = React.useState([]);
     |         ^
   8 | 
   9 |   info = async () => {
  10 |     try {

【问题讨论】:

    标签: javascript node.js reactjs postgresql express


    【解决方案1】:

    你不能在基于类的组件中使用 React 钩子,将你的类变成一个纯函数组件,如下所示:

    import React, { useEffect, useState } from "react";
    import Table from "./Table";
    import Nav from "./Navi";
    import TemplateList from "./TemplateList";
    import { Tab, Tabs } from "react-bootstrap";
    
    const Dashboard = (props) => {
      const [tdata, setTdata] = useState([]);
    
      const info = async () => {
        try {
          const response = await fetch("http://localhost:8080/dashboard");
          const dataServer = await response.json();
          setTdata(dataServer);
        } catch (err) {
          console.error(err.message);
        }
      };
      console.log(tdata);
    
      useEffect(() => {
        info();
      }, []);
    
      return {
        <div>
           /* your JSX here */
        </div>
      };
    };
    

    更多关于钩子的信息在这里:https://reactjs.org/docs/hooks-intro.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 2020-02-17
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      • 2022-01-02
      • 2017-04-30
      相关资源
      最近更新 更多