在简单的 CRUD 应用程序之外构建 Django/React 项目概念

问题描述

我已经开始了一个带有几个应用程序的 Django 项目,其中一个包含我的反应。我想弄清楚最佳实践/专业偏好,因为它与文件结构和基于使用 Django 和 React 的全栈应用程序中的 url 区分视图有关。现在,似乎与 Django Rest API 交互的唯一 js 文件称为 App.js,但我显然想对此进行扩展并创建与我的后端交互的不同组件。我是否只是从每个组件文件中的 api 中获取数据?此外,为了创建不同的视图,似乎在我的 index.js 中,我为我的 main.js 加载了已编译的 webpack 的静态文件。如果我想有不同的页面,我是否需要为每个页面视图在 main.js 文件中编译一个 webpack?

假设我想创建一个关于页面一个主页。创建两个都有反应的 django 应用程序是最佳实践,一个用作页面视图,一个用作主页视图?如果没有,您有什么建议?

这是我的 App.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}
              <h1>Hi</h1>
            </li>
          );
        })}
      </ul>
    );
  }
}

export default App;

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

我的 index.js

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

此外,在我的 index.html 文件中,我正在关注的教程的创建者补充说“React 将在此处加载”这只是调用每个组件的 div 的 id 吗?

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

提前致谢。希望这将有助于那些想要使用 Django 和 React 创建全栈应用程序的人了解未来的文件结构和最佳实践。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)