首页 > 解决方案 > 无法找出 App.js 中的语法错误

问题描述

我正在使用本教程使用 Django 中内置的 API 为前端安装 React。

https://sweetcode.io/how-use-djang-react-ap/

到目前为止,我的这个项目的存储库在这里:

https://github.com/AlexMercedCoder/DjangoReactCRM

当我 npm run dev 在 App.js 中遇到语法错误时,我玩过它,但似乎无法弄清楚。我得到的错误是。

ERROR in ./frontend/src/components/App.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: 
C:\Users\alexm\projects\DjangoReactCRM\drcrm\frontend\src
\components\App.js: Unexpected token, expected "," (29:6)

  27 |
  28 | wrapper ? ReactDOM.render(<app>, wrapper) : null;
> 29 | </app>

应用程序.js

import React, { Component } from "react";
import ReactDOM from "react-dom";


class App extends Component {

  state = {
      data: ''
  };

    componentDidMount() {
       fetch("/api")
          .then(response => {
           return response.json();
        })
        .then(data => this.setState({ data: JSON.stringify(data)}));
  }

   render(){

      return (
            <p>Jason data = {this.state.data}</p>
      )
  }
}


wrapper ? ReactDOM.render(<app>, wrapper) : null;
</app>

标签: djangoreactjsdjango-rest-framework

解决方案


您的组件存在三个问题。

  1. 我猜wrapper应该是document.getElementById("root")?即使这样,三元条件也没有意义。它应该是这样的:
ReactDOM.render(
 <App />,
document.getElementById("root")
)
  1. 您将组件定义为App,但ReactDOM.render您正在使用app
  2. 你有</app>在文件的末尾。在这种情况下它什么也没做。

推荐阅读