博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
django react_使用Django和React构建待办事项应用程序
阅读量:2510 次
发布时间:2019-05-11

本文共 32482 字,大约阅读时间需要 108 分钟。

django react

Web development has grown rapidly over the last decade, and there's a long list of frameworks to choose from when building your projects. A developer’s decision on what framework(s) to use for a project is usually influenced by a number of specific factors; one of which is the complexity of the framework in defining the separate tasks that make up that project.

Web开发在过去十年中发展Swift,在构建项目时,有很多框架可供选择。 开发人员对项目使用哪种框架的决定通常受许多特定因素的影响; 其中之一是框架的复杂性,难以定义组成该项目的单独任务。

In this tutorial, we will look at how to build a Todo application using Django and React. I have chosen these frameworks because:

在本教程中,我们将研究如何使用Django和React构建Todo应用程序。 我选择这些框架是因为:

  1. React is a framework of JavaScript that is great for developing SPAs (single page applications) and it has a large developer community, so I don’t have to waste good weeks stuck on an error.

    React是一个JavaScript框架,非常适合开发SPA(单页应用程序),并且拥有庞大的开发人员社区,因此我不必浪费很多时间来解决错误。
  2. Django is a web framework of Python that simplifies common practices in web development. Django has you covered, from authentication to session management, it will save you loads of time.

    Django是Python的网络框架,可简化网络开发中的常见做法。 Django涵盖了从身份验证到会话管理的所有内容,它将为您节省大量时间。

Django and React make an awesome combination to build this application with, owing to React’s SPA optimizations, and Django’s long list of helpful libraries. For this application to work correctly, the frontend (React) will have to interact with the backend i.e retrieve and store data. To create the interface for interaction, we will build an API (Application Programming Interface) on the backend, using the Django REST framework (DRF).

由于React的SPA优化以及Django的有用库的长列表,Django和React进行了很棒的组合来构建此应用程序。 为了使该应用程序正常工作,前端(React)将必须与后端进行交互,即检索和存储数据。 为了创建交互界面,我们将使用Django REST框架(DRF)在后端构建一个API(应用程序编程接口)。

At the end of this tutorial, we will have the final application that looks like this:

在本教程的最后,我们将拥有最终的应用程序,如下所示:

The source code for this tutorial is available on GitHub.

本教程的源代码可以 GitHub上。

( )

To follow along with this tutorial, you will need the following installed on your machine:

要继续学习本教程,您需要在计算机上安装以下软件:

  1. Python.

    Python。
  2. Pip.

    点子
  3. Pipenv.

    Pipenv。

Pipenv is a production-ready tool that aims to bring the best of all packaging worlds to the Python world. It harnesses Pipfile, pip, and virtualenv into one single command.

Pipenv是可用于生产的工具,旨在将所有包装领域的精华带入Python世界。 它将Pipfile,pip和virtualenv整合到一个命令中。

Let’s dive in and get started!

让我们开始吧!

( )

In this section, we will set up the backend and create all the folders that we need to get things up and running, so launch a new instance of a terminal and create the project’s directory by running this command:

在本节中,我们将设置后端并创建启动和运行所需的所有文件夹,因此启动终端的新实例并通过运行以下命令创建项目的目录:

$mkdir django-todo-react

Next, we will navigate into the directory:

接下来,我们将导航到目录:

$cd django-todo-react

Now we will install Pipenv using pip and activate a new virtual environment:

现在,我们将使用pip安装Pipenv并激活一个新的虚拟环境:

$ pipinstall pipenv$ pipenv shell

Note: You should skip the first command if you already have Pipenv installed.

注意:如果已经安装了Pipenv,则应跳过第一个命令。

Let’s install Django using Pipenv then create a new project called backend:

让我们使用Pipenv安装Django,然后创建一个名为backend的新项目:

$ pipenvinstall django$ django-admin startproject backend

Next, we will navigate into the newly created backend folder and start a new application called todo. We will also run migrations and start up the server:

接下来,我们将导航到新创建的后端文件夹并启动一个名为todo的新应用程序。 我们还将运行迁移并启动服务器:

$cd backend$ python manage.py startapp todo$ python manage.py migrate$ python manage.py runserver

At this point, if all the commands were entered correctly, we should see an instance of a Django application running on this address —

此时,如果所有命令输入正确,我们应该看到在该地址上运行的Django应用程序实例—

注册Todo应用程序 (Registering the Todo application)

We are done with the basic setup for the backend, let’s start with the more advanced things like registering the todo application as an installed app so that Django can recognise it. Open the backend/settings.py file and update the INSTALLED_APPS section as so:

我们已经完成了后端的基本设置,让我们从更高级的事情开始,例如将todo应用程序注册为已安装的应用程序,以便Django可以识别它。 打开backend/settings.py文件,并按以下方式更新INSTALLED_APPS部分:

# backend/settings.py    # Application definition    INSTALLED_APPS = [        'django.contrib.admin',        'django.contrib.auth',        'django.contrib.contenttypes',        'django.contrib.sessions',        'django.contrib.messages',        'django.contrib.staticfiles',        'todo' # add this       ]

定义Todo模型 (Defining the Todo model)

Let's create a model to define how the Todo items should be stored in the database, open the todo/models.py file and update it with this snippet:

让我们创建一个模型来定义Todo项应如何存储在数据库中,打开todo/models.py文件并使用以下代码片段对其进行更新:

# todo/models.py    from django.db import models    # Create your models here.    # add this    class Todo(models.Model):      title = models.CharField(max_length=120)      description = models.TextField()      completed = models.BooleanField(default=False)      def _str_(self):        return self.title

The code snippet above describes three properties on the Todo model:

上面的代码段描述了Todo模型的三个属性:

  • Title

    标题

  • Description

    描述

  • Completed

    已完成

The completed property is the status of a task; a task will either be completed or not completed at any time. Because we have created a Todo model, we need to create a migration file and apply the changes to the database, so let’s run these commands:

完成的属性是任务的状态; 任务将随时完成或未完成。 因为我们已经创建了Todo模型,所以我们需要创建一个迁移文件并将更改应用到数据库,因此让我们运行以下命令:

$ python manage.py makemigrations todo$ python manage.py migrate todo

We can test to see that CRUD operations work on the Todo model we created using the admin interface that Django provides out of the box, but first, we will do a little configuration.

我们可以测试一下CRUD操作是否可以在使用Django开箱即用的管理界面创建的Todo模型上运行,但是首先,我们将进行一些配置。

Open the todo/admin.py file and update it accordingly:

打开todo/admin.py文件并相应地更新它:

# todo/admin.py    from django.contrib import admin    from .models import Todo # add this    class TodoAdmin(admin.ModelAdmin):  # add this      list_display = ('title', 'description', 'completed') # add this    # Register your models here.    admin.site.register(Todo, TodoAdmin) # add this

We will create a superuser account to access the admin interface with this command:

我们将使用以下命令创建一个超级用户帐户来访问管理界面:

$ python manage.py createsuperuser

You will be prompted to enter a username, email and password for the superuser. Be sure to enter details that you can remember because you will need them to log in to the admin dashboard shortly.

系统将提示您输入超级用户的用户名,电子邮件和密码。 确保输入您可以记住的详细信息,因为您将需要它们很快登录到管理仪表板。

Let’s start the server once more and log in on the address —

让我们再次启动服务器并登录以下地址:

$ python manage.py runserver

We can create, edit and delete Todo items using this interface. Let’s go ahead and create some:

我们可以使用此界面创建,编辑和删除待办事项。 让我们继续创建一些:

Awesome work so far, be proud of what you’ve done! In the next section, we will see how we can create the API using the Django REST framework.

迄今为止的出色工作,为您所做的一切感到自豪! 在下一节中,我们将看到如何使用Django REST框架创建API。

( )

Now, we will quit the server (CONTROL-C) then install the djangorestframework and django-cors-headers using Pipenv:

现在,我们将退出服务器(CONTROL-C),然后使用Pipenv安装djangorestframeworkdjango-cors-headers

$ pipenvinstall djangorestframework django-cors-headers

We need to add rest_framework and corsheaders to the list of installed applications, so open the backend/settings.py file and update the INSTALLED_APPS and MIDDLEWARE sections accordingly:

我们需要将rest_frameworkcorsheaders添加到已安装的应用程序列表中,因此打开backend/settings.py文件并相应地更新INSTALLED_APPSMIDDLEWARE部分:

# backend/settings.py    # Application definition    INSTALLED_APPS = [        'django.contrib.admin',        'django.contrib.auth',        'django.contrib.contenttypes',        'django.contrib.sessions',        'django.contrib.messages',        'django.contrib.staticfiles',        'corsheaders',            # add this        'rest_framework',         # add this         'todo',      ]    MIDDLEWARE = [        'corsheaders.middleware.CorsMiddleware',    # add this        'django.middleware.security.SecurityMiddleware',        'django.contrib.sessions.middleware.SessionMiddleware',        'django.middleware.common.CommonMiddleware',        'django.middleware.csrf.CsrfViewMiddleware',        'django.contrib.auth.middleware.AuthenticationMiddleware',        'django.contrib.messages.middleware.MessageMiddleware',        'django.middleware.clickjacking.XFrameOptionsMiddleware',    ]

Add this code snippet to the bottom of the backend/settings.py file:

将此代码段添加到backend/settings.py文件的底部:

# we whitelist localhost:3000 because that's where frontend will be served    CORS_ORIGIN_WHITELIST = (         'localhost:3000/'     )

Django-cors-headers is a python library that will help in preventing the errors that we would normally get due to CORS. rules. In the CORS_ORIGIN_WHITELIST snippet, we whitelisted localhost:3000 because we want the frontend (which will be served on that port) of the application to interact with the API.

Django-cors-headers是一个python库,它将有助于防止我们通常会由于CORS而收到错误。 规则。 在CORS_ORIGIN_WHITELIST片段中,我们将localhost:3000列入了白名单,因为我们希望应用程序的前端(将在该端口上提供服务)与API进行交互。

为Todo模型创建序列化器 (Creating serializers for the Todo model)

We need serializers to convert model instances to JSON so that the frontend can work with the received data easily. We will create a todo/serializers.py file:

我们需要序列化程序将模型实例转换为JSON,以便前端可以轻松处理接收到的数据。 我们将创建一个todo/serializers.py文件:

$touch todo/serializers.py

Open the serializers.py file and update it with the following code.

打开serializers.py文件,并使用以下代码对其进行更新。

# todo/serializers.py    from rest_framework import serializers    from .models import Todo    class TodoSerializer(serializers.ModelSerializer):      class Meta:        model = Todo        fields = ('id', 'title', 'description', 'completed')

In the code snippet above, we specified the model to work with and the fields we want to be converted to JSON.

在上面的代码片段中,我们指定了要使用的模型以及要转换为JSON的字段。

创建视图 (Creating the View)

We will create a TodoView class in the todo/views.py file, so update it with the following code:

我们将在todo/views.py文件中创建一个TodoView类,因此请使用以下代码对其进行更新:

# todo/views.py    from django.shortcuts import render    from rest_framework import viewsets          # add this    from .serializers import TodoSerializer      # add this    from .models import Todo                     # add this    class TodoView(viewsets.ModelViewSet):       # add this      serializer_class = TodoSerializer          # add this      queryset = Todo.objects.all()              # add this

The viewsets base class provides the implementation for CRUD operations by default, what we had to do was specify the serializer class and the query set.

默认情况下, viewsets基类提供CRUD操作的实现,我们要做的是指定序列化器类和查询集。

Head over to the backend/urls.py file and completely replace it with the code below. This code specifies the URL path for the API:

转至backend/urls.py文件,并将其完全替换为以下代码。 此代码指定API的URL路径:

# backend/urls.py    from django.contrib import admin    from django.urls import path, include                 # add this    from rest_framework import routers                    # add this    from todo import views                            # add this    router = routers.DefaultRouter()                      # add this    router.register(r'todos', views.TodoView, 'todo')     # add this    urlpatterns = [        path('admin/', admin.site.urls),         path('api/', include(router.urls))                # add this    ]

This is the final step that completes the building of the API, we can now perform CRUD operations on the Todo model. The router class allows us to make the following queries:

这是完成API构建的最后一步,我们现在可以在Todo模型上执行CRUD操作。 路由器类使我们可以进行以下查询:

  • /todos/ - This returns a list of all the Todo items (Create and Read operations can be done here).

    /todos/ -这将返回所有Todo项目的列表(可以在此处完成创建和读取操作)。

  • /todos/id - this returns a single Todo item using the id primary key (Update and Delete operations can be done here).

    /todos/id id-使用id主键返回一个Todo项(可以在此处完成Update和Delete操作)。

Let’s restart the server and visit this address — :

让我们重新启动服务器并访问该地址 :

$ python manage.py runserver

We can create a new todo item using the interface:

我们可以使用界面创建一个新的待办事项:

If the Todo item is created successfully, you will see a screen like this:

如果“待办事项”项创建成功,您将看到类似以下的屏幕:

We can also perform DELETE and UPDATE operations on specific Todo items using their id primary keys. To do this, we will visit an address with this structure /api/todos/id. Let’s try with this address — :

我们还可以使用其id主键对特定的Todo项目执行DELETE和UPDATE操作。 为此,我们将访问具有/api/todos/id.结构的地址/api/todos/id. 让我们尝试使用该地址 :

That’s all for the backend of the application, now we can move on to fleshing out the frontend.

这就是应用程序后端的全部内容,现在我们可以继续充实前端。

( )

We have our backend running as it should, now we will create our frontend and make it communicate with the backend over the interface that we created.

我们让后端正常运行,现在我们将创建前端,并使其通过我们创建的接口与后端进行通信。

Since we are building our frontend using React, we want to use the create-react-app CLI tool because it registers optimal settings and several benefits such as Hot reloading and Service workers. We will install the create-react-app CLI (command line interface) tool globally with this command:

由于我们使用React构建前端,因此我们希望使用create-react-app CLI工具,因为它注册了最佳设置并具有诸如热重载和服务工作者之类的诸多好处。 我们将使用以下命令在全局安装create-react-app CLI(命令行界面)工具:

$npm install -g create-react-app

Let’s navigate back into the parent working directory — django-todo-react — of our application and create a new React application called frontend:

让我们导航回应用程序的父工作目录django-todo-react ,并创建一个名为frontend的新React应用程序:

$ create-react-app frontend

It will probably take a while for all of the dependencies to be installed, once it’s over, your terminal should look something like this:

安装所有依赖项可能需要一段时间,一旦结束,终端应该看起来像这样:

Run the following commands to navigate into the working directory and start the frontend server

运行以下命令以导航到工作目录并启动前端服务器

$cd frontend$ yarn start

Note: If you don’t have Yarn installed, you can find installation instructions here.

注意:如果您尚未安装Yarn,则可以在此处找到安装说明。

We can now visit this address — — and we will see the default React screen:

现在,我们可以访问该地址 ,我们将看到默认的React屏幕:

We will pull in bootstrap and reactstrap to spice the UI up a bit:

我们将reactstrap bootstrapreactstrap来为UI reactstrap

$ yarn add bootstrap reactstrap

Let’s open the src/index.css file and replace the styles there with this one:

让我们打开src/index.css文件,并用此替换其中的样式:

/__ frontend/src/index.css  __/    body {
margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; background-color: #282c34; } .todo-title {
cursor: pointer; } .completed-todo {
text-decoration: line-through; } .tab-list > span {
padding: 5px 8px; border: 1px solid #282c34; border-radius: 10px; margin-right: 5px; cursor: pointer; } .tab-list > span.active {
background-color: #282c34; color: #ffffff; }

We will import Bootstrap’s stylesheet in src/index.js so that we can use Bootstrap’s classes:

我们将在src/index.js导入Bootstrap的样式表,以便我们可以使用Bootstrap的类:

// frontend/src/index.js      import React from 'react';      import ReactDOM from 'react-dom';      import 'bootstrap/dist/css/bootstrap.min.css';       // add this      import './index.css';      import App from './App';      import * as serviceWorker from './serviceWorker';      ReactDOM.render(
, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: http://bit.ly/CRA-PWA serviceWorker.unregister();

Let’s replace the code in src/App.js with this one:

让我们用以下代码替换src/App.js的代码:

// frontend/src/App.js    import React, { Component } from "react";    const todoItems = [      {        id: 1,        title: "Go to Market",        description: "Buy ingredients to prepare dinner",        completed: true      },      {        id: 2,        title: "Study",        description: "Read Algebra and History textbook for upcoming test",        completed: false      },      {        id: 3,        title: "Sally's books",        description: "Go to library to rent sally's books",        completed: true      },      {        id: 4,        title: "Article",        description: "Write article on how to use django with react",        completed: false      }    ];    class App extends Component {      constructor(props) {        super(props);        this.state = {          viewCompleted: false,          todoList: todoItems        };      }      displayCompleted = status => {        if (status) {          return this.setState({ viewCompleted: true });        }        return this.setState({ viewCompleted: false });      };      renderTabList = () => {        return (          
this.displayCompleted(true)} className={this.state.viewCompleted ? "active" : ""} > complete
this.displayCompleted(false)} className={this.state.viewCompleted ? "" : "active"} > Incomplete
); }; renderItems = () => { const { viewCompleted } = this.state; const newItems = this.state.todoList.filter( item => item.completed == viewCompleted ); return newItems.map(item => (
  • {item.title}
  • )); }; render() { return (

    Todo app

    {this.renderTabList()}
      {this.renderItems()}
    ); } } export default App;

    Okay, that’s a lot of code 😅, but there’s no need to be afraid now, we haven’t started interacting with the backend API, so we included default values to populate the Todo list. The `renderTabList()` function renders two spans which help control which set of items are displayed i.e clicking on the completed tab shows completed tasks and the same for the incomplete tab.

    好的,有很多代码😅,但是现在不必担心,我们还没有开始与后端API进行交互,因此我们包括了默认值以填充待办事项列表。 “ renderTabList()”函数呈现两个范围,以帮助控制显示哪些项目集,即,单击“完成”选项卡上的将显示已完成的任务,而单击“未完成”选项卡则显示相同的任务。

    If we visit the React frontend application now, it will look like this:

    如果我们现在访问React前端应用程序,它将看起来像这样:

    To handle actions such as adding and editing tasks, we will use a modal, so let's create a Modal component in a components folder.

    为了处理诸如添加和编辑任务之类的操作,我们将使用模态,因此让我们在components文件夹中创建一个Modal组件。

    Create a components folder in the src directory:

    src目录中创建一个components文件夹:

    $mkdir src/components

    Create a Modal.js file in the components folder:

    在components文件夹中创建一个Modal.js file

    $touch src/components/Modal.js

    Open the Modal.js file and populate it with the code snippet below:

    打开Modal.js文件,并使用下面的代码片段进行填充:

    // frontend/src/components/Modal.js    import React, { Component } from "react";    import {      Button,      Modal,      ModalHeader,      ModalBody,      ModalFooter,      Form,      FormGroup,      Input,      Label    } from "reactstrap";    export default class CustomModal extends Component {      constructor(props) {        super(props);        this.state = {          activeItem: this.props.activeItem        };      }      handleChange = e => {        let { name, value } = e.target;        if (e.target.type === "checkbox") {          value = e.target.checked;        }        const activeItem = { ...this.state.activeItem, [name]: value };        this.setState({ activeItem });      };      render() {        const { toggle, onSave } = this.props;        return (          
    Todo Item
    ); } }

    We created a CustomModal class and it nests the Modal component that is derived from the reactstrap library. We also defined three fields in the form:

    我们创建了一个CustomModal类,它嵌套了从reactstrap库派生的Modal组件。 我们还以以下形式定义了三个字段:

    • Title

      标题

    • Description

      描述

    • Completed

      已完成

    These are the same fields that we defined as properties on the Todo model in the backend.

    这些是我们在后端的Todo模型上定义为属性的字段。

    Here’s how the CustomModal works, it receives activeItem, toggle and onSave as props.

    这是CustomModal工作方式,它接收activeItemtoggle和onSave作为道具。

    1. activeItem represents the Todo item to be edited.

      activeItem表示要编辑的待办事项。
    2. toggle is a function used to control the Modal’s state i.e open or close the modal.

      toggle是用于控制模态的功能,即打开或关闭模态。
    3. onSave is a function that is called to save the edited values of the Todo item.

      onSave是一个用于保存Todo项的已编辑值的函数。

    Next, we will import the CustomModal component into the App.js file. Head over to the src/App.js file and replace it completely with this updated version:

    接下来,我们将CustomModal组件导入App.js文件。 转至src/App.js文件,并将其完全替换为此更新版本:

    // frontend/src/App.js    import React, { Component } from "react";    import Modal from "./components/Modal";    const todoItems = [      {        id: 1,        title: "Go to Market",        description: "Buy ingredients to prepare dinner",        completed: true      },      {        id: 2,        title: "Study",        description: "Read Algebra and History textbook for upcoming test",        completed: false      },      {        id: 3,        title: "Sally's books",        description: "Go to library to rent sally's books",        completed: true      },      {        id: 4,        title: "Article",        description: "Write article on how to use django with react",        completed: false      }    ];    class App extends Component {      constructor(props) {        super(props);        this.state = {          modal: false,          viewCompleted: false,          activeItem: {            title: "",            description: "",            completed: false          },          todoList: todoItems        };      }      toggle = () => {        this.setState({ modal: !this.state.modal });      };      handleSubmit = item => {        this.toggle();        alert("save" + JSON.stringify(item));      };      handleDelete = item => {        alert("delete" + JSON.stringify(item));      };      createItem = () => {        const item = { title: "", description: "", completed: false };        this.setState({ activeItem: item, modal: !this.state.modal });      };      editItem = item => {        this.setState({ activeItem: item, modal: !this.state.modal });      };      displayCompleted = status => {        if (status) {          return this.setState({ viewCompleted: true });        }        return this.setState({ viewCompleted: false });      };      renderTabList = () => {        return (          
    this.displayCompleted(true)} className={this.state.viewCompleted ? "active" : ""} > complete
    this.displayCompleted(false)} className={this.state.viewCompleted ? "" : "active"} > Incomplete
    ); }; renderItems = () => { const { viewCompleted } = this.state; const newItems = this.state.todoList.filter( item => item.completed === viewCompleted ); return newItems.map(item => (
  • {item.title}
  • )); }; render() { return (

    Todo app

    {this.renderTabList()}
      {this.renderItems()}
    {this.state.modal ? (
    ) : null}
    ); } } export default App;

    We can now revisit the React frontend, this is what the application should resemble at this point:

    现在,我们可以重新访问React前端,这是应用程序此时的外观:

    If we attempt to edit and save a Todo item, we will get an alert showing the Todo item’s object. Clicking on save, and delete will perform the fitting actions on the Todo item.

    如果我们尝试编辑和保存Todo项,则会收到显示Todo项对象的警报。 单击保存并删除将对“待办事项”项执行拟合操作。

    We will now modify the application so that it interacts with the Django API we built in the previous section. Let’s start by starting up the backend server (on a different instance of the terminal) if it isn’t already running:

    现在,我们将修改应用程序,使其与上一节中构建的Django API交互。 让我们首先启动后端服务器(在终端的另一个实例上)(如果尚未运行):

    $ python manage.py runserver

    Note: This command has to be run in the `backend` directory in a virtual Pipenv shell.

    注意:该命令必须在虚拟Pipenv shell的“后端”目录中运行。

    For us to make requests to the API endpoints on the backend server, we will install a JavaScript library called axios. Let’s pull in `axios using Yarn:

    为了向后端服务器上的API端点发出请求,我们将安装一个名为axios.JavaScript库axios. 让我们使用Yarn来引入`axios:

    $ yarn add axios

    Once axios is successfully installed, head over to the frontend/package.json file and add a proxy like so:

    成功安装axios frontend/package.json文件并添加一个代理,如下所示:

    // frontend/package.json[...]       "name": "frontend",      "version": "0.1.0",      "private": true,      "proxy": "http://localhost:8000",      "dependencies": {
    "axios": "^0.18.0", "bootstrap": "^4.1.3", "react": "^16.5.2", "react-dom": "^16.5.2", "react-scripts": "2.0.5", "reactstrap": "^6.5.0" }, [...]

    The proxy will help in tunnelling API requests to where the Django application will handle them, so we can write the requests like this in the frontend:

    代理将帮助将API请求隧穿到Django应用程序将在其中处理的 ,因此我们可以在前端中编写如下请求:

    axios.get("/api/todos/")

    Instead of this:

    代替这个:

    axios.get("http://localhost:8000/api/todos/")

    Note: You might need to restart the development server for the proxy to register with the application.

    注意:您可能需要重新启动开发服务器,代理才能向应用程序注册。

    We will modify the frontend/src/App.js one last time so that it doesn’t use the hardcoded items from the array anymore, but requests data from the backend server and lists them instead. We want to also ensure that all CRUD operations send requests to the backend server instead of interacting with the dummy data.

    我们将最后一次修改frontend/src/App.js以便它不再使用数组中的硬编码项目,而是从后端服务器请求数据并列出它们。 我们还希望确保所有CRUD操作都将请求发送到后端服务器,而不是与虚拟数据进行交互。

    Open the file and replace it with this final version:

    打开文件并将其替换为最终版本:

    // frontend/src/App.js    import React, { Component } from "react";    import Modal from "./components/Modal";    import axios from "axios";    class App extends Component {      constructor(props) {        super(props);        this.state = {          viewCompleted: false,          activeItem: {            title: "",            description: "",            completed: false          },          todoList: []        };      }      componentDidMount() {        this.refreshList();      }      refreshList = () => {        axios          .get("http://localhost:8000/api/todos/")          .then(res => this.setState({ todoList: res.data }))          .catch(err => console.log(err));      };      displayCompleted = status => {        if (status) {          return this.setState({ viewCompleted: true });        }        return this.setState({ viewCompleted: false });      };      renderTabList = () => {        return (          
    this.displayCompleted(true)} className={this.state.viewCompleted ? "active" : ""} > complete
    this.displayCompleted(false)} className={this.state.viewCompleted ? "" : "active"} > Incomplete
    ); }; renderItems = () => { const { viewCompleted } = this.state; const newItems = this.state.todoList.filter( item => item.completed === viewCompleted ); return newItems.map(item => (
  • {item.title}
  • )); }; toggle = () => { this.setState({ modal: !this.state.modal }); }; handleSubmit = item => { this.toggle(); if (item.id) { axios .put(`http://localhost:8000/api/todos/${item.id}/`, item) .then(res => this.refreshList()); return; } axios .post("http://localhost:8000/api/todos/", item) .then(res => this.refreshList()); }; handleDelete = item => { axios .delete(`http://localhost:8000/api/todos/${item.id}`) .then(res => this.refreshList()); }; createItem = () => { const item = { title: "", description: "", completed: false }; this.setState({ activeItem: item, modal: !this.state.modal }); }; editItem = item => { this.setState({ activeItem: item, modal: !this.state.modal }); }; render() { return (

    Todo app

    {this.renderTabList()}
      {this.renderItems()}
    {this.state.modal ? (
    ) : null}
    ); } } export default App;

    The refreshList() function is reusable that is called each time an API request is completed. It updates the Todo list to display the most recent list of added items.

    每次完成API请求时,都会调用refreshList()函数可重用。 它将更新“待办事项”列表以显示最近添加的项目列表。

    The handleSubmit() function takes care of both the create and update operations. If the item passed as the parameter doesn’t have an id, then it has probably not been created, so the function creates it.

    handleSubmit()函数负责创建和更新操作。 如果作为参数传递的项目没有ID,则可能尚未创建,因此该函数将创建它。

    Congratulations! We have just built the fontend successfully.

    恭喜你! 我们已经成功构建了fontend。

    ( )

    Let’s start the backend server on a terminal instance that’s sourced into the Pipenv virtual shell and pointed to the backend directory:

    让我们在源于Pipenv虚拟外壳程序并指向后端目录的终端实例上启动后端服务器:

    $ python manage.py runserver

    We also need to start the frontend development server:

    我们还需要启动前端开发服务器:

    $ yarn start

    We can visit the application on this address — — to see that it works:

    我们可以在以下地址( 上访问该应用程序,以查看它是否有效:

    We’ve come to the end of this tutorial and learnt how to configure Django and React to interact correctly with each other. We also saw some of the benefits that come with bootstrapping a React application using the create-react-app tool, such as Hot-reloading which is basically the feature that makes it possible for the web app to reload on its own whenever a change is detected.

    我们已经到了本教程的结尾,学习了如何配置Django和React使其正确交互。 我们还看到了使用create-react-app工具引导React应用程序带来的一些好处,例如热重载,它基本上是使更改后的Web应用程序能够自行重载的功能检测到。

    The source code for this tutorial is available on GitHub.

    本教程的源代码可以 GitHub上。

    翻译自:

    django react

    转载地址:http://qhuwd.baihongyu.com/

    你可能感兴趣的文章
    适用于带文字 和图片的垂直居中方法
    查看>>
    Part 2 - Fundamentals(4-10)
    查看>>
    使用Postmark测试后端存储性能
    查看>>
    NSTextView 文字链接的定制化
    查看>>
    第五天站立会议内容
    查看>>
    CentOs7安装rabbitmq
    查看>>
    (转))iOS App上架AppStore 会遇到的坑
    查看>>
    解决vmware与主机无法连通的问题
    查看>>
    做好产品
    查看>>
    项目管理经验
    查看>>
    笔记:Hadoop权威指南 第8章 MapReduce 的特性
    查看>>
    JMeter响应数据出现乱码的处理-三种解决方式
    查看>>
    获取设备实际宽度
    查看>>
    Notes on <High Performance MySQL> -- Ch3: Schema Optimization and Indexing
    查看>>
    Alpha冲刺(10/10)
    查看>>
    数组Array的API2
    查看>>
    为什么 Redis 重启后没有正确恢复之前的内存数据
    查看>>
    No qualifying bean of type available问题修复
    查看>>
    第四周助教心得体会
    查看>>
    spfile
    查看>>