首页 > 解决方案 > 在 reactjs 前端看不到来自 django 的数据

问题描述

我是新来的反应。我正在构建 django + react web-application 项目的完整代码https://github.com/mascai/django_examples/tree/master/02_django_react

当我提出请求时,http://127.0.0.1:8001/api/lead/我会看到来自 Django 的有效数据。但是当我去的时候http://127.0.0.1:8001我没有看到没有看到任何数据。

我认为前端的问题。

index.js

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

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      loaded: false,
      placeholder: "Loading"
    };
  }

  componentDidMount() {
    fetch("api/lead")
      .then(response => {
        if (response.status > 400) {
          return this.setState(() => {
            return { placeholder: "Something went wrong!" };
          });
        } 
        return response.json();
      })
      .then(data => {
        this.setState(() => {
          return {
            data,
            loaded: true
          };
        });
      });
  }

  render() {
    return (
      <ul>
        {this.state.data.map(contact => {
          return (
            <li key={contact.id}>
              {contact.name} - {contact.email}
            </li>
          );
        })}
      </ul>
    );
  }
}

export default App;

const container = document.getElementById("app");
render(<App />, container);

index.html(看起来不错)

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Django REST with React
</head>
<body>
<div id="app">
    <!-- React will load here -->
</div>
</body>
{% load static %}
<script src="{% static "frontend/main.js" %}"></script>
</html>

标签: reactjsdjango

解决方案


您忘记了标题中的结束标签index.html

<title>Django REST with React</title>

并且脚本引号应该是这样的(注意双引号和单引号):

<script src="{% static 'frontend/main.js' %}"></script>

另一个问题是,当你构建你的 React 应用程序时,它会被放置在static/frontend/main.js/main.js. 因此,您不仅要创建一个名为 的文件main.js,还要创建一个名为main.js.

为了解决这个问题,首先删除static/frontend文件夹的内容(删除main.js目录)。

然后转到package.json并将脚本中的输出路径更改为

  "scripts": {
    "dev": "webpack --mode development ./src/index.js --output-path ./static/frontend",
    "build": "webpack --mode production ./src/index.js --output-path ./static/frontend"
  },

我还建议将<h1>带有随机文本的标签放入您的组件中,以便您可以查看您的组件是否实际呈现。

最后使用这两个命令之一编译您的反应应用程序。


推荐阅读