博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
react 执行入口_如何使用React执行CRUD操作
阅读量:2523 次
发布时间:2019-05-11

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

react 执行入口

by Zafar Saleem

通过Zafar Saleem

如何使用React执行CRUD操作 (How to perform CRUD operations using React)

In my previous articles, we have already written the same Todo application using and . Now it’s time to take this same example a little further and use an even more popular framework: React. This example assumes that you’ve already installed and on your system.

在之前的文章中,我们已经使用和编写了相同的Todo应用程序。 现在是时候进一步研究这个例子,并使用一个更流行的框架:React。 本示例假定您已经在系统上安装了和 。

First of all, let's create a new React app with this command.

首先,让我们使用此命令创建一个新的React应用。

create-react-app todo

Give it a few seconds and then you should have a todo folder in your file system. CD into that folder.

给它几秒钟,然后在文件系统中应该有一个todo文件夹。 CD放入该文件夹。

First thing that is created is a new file called Todo.js inside the src/ folder. Here is the code in that file:

创建的第一件事是src /文件夹中的一个名为Todo.js的新文件。 这是该文件中的代码:

import React, { Component } from 'react';
class Todo extends Component {     render() {        return(

This message is from Todo component

) } }
export default Todo;

First, we are importing React and Component from the React core.

首先,我们从React导入ReactComponent 核心。

Then we are creating a Todo component which extends from Component.

然后我们创建一个从Component扩展的Todo 组件

The todo component has a render method which renders JSX with an h1 element and the text “This message is from Todo component”.

todo组件具有一个render方法,该方法使用h1元素和文本“此消息来自Todo组件”来呈现JSX。

Finally, we are exporting this component to use it in the rest of our project.

最后,我们导出该组件以在项目的其余部分中使用它。

Now open src/App.js file. We need to import our newly created Todo component after the import of the App.css file.

现在打开src / App.js文件。 导入App.css文件后,我们需要导入新创建的Todo组件。

Once there, now use this component inside the render method of the App component.

到达那里后,现在在App组件的render方法内使用此组件。

import React, { Component } from 'react';import logo from './logo.svg';import './App.css';
// import Todo component hereimport Todo from './Todo';
class App extends Component {
constructor(props) {    super(props);
this.state = {      show: false    };  }
render() {    // use Todo component inside render method.    return (      
); }}
export default App;

Now that we have the basic Todo Component file and have imported it in the App component and used it, it’s time to add some mockData. This time we are going to use React states to work with our data. This makes things easier in order to perform CRUD operations and update the view accordingly. Add this code to the Todo component:

现在我们有了基本的Todo Component文件,并将其导入到App组件中并使用了它,现在该添加一些模拟数据了 。 这次,我们将使用React状态来处理我们的数据。 这使执行CRUD操作并相应地更新视图变得更加容易。 将此代码添加到Todo组件:

class Todo extends Component {  state = {    edit: false,    id: null,    mockData: [{      id: '1',      title: 'Buy Milk',      done: false,      date: new Date()    }, {      id: '2',      title: 'Meeting with Ali',      done: false,      date: new Date()    }, {      id: '3',      title: 'Tea break',      done: false,      date: new Date()    }, {      id: '4',      title: 'Go for a run.',      done: false,      date: new Date()    }]  }}

State is like a data store to the ReactJS component. It is mostly used to update the component when a user performs some action like clicking button, typing some text, pressing some key, etc.

状态就像是ReactJS组件的数据存储。 当用户执行某些操作(例如clicking buttontyping some textpressing some key等)时,它通常用于更新组件。

The above state can also be placed inside the constructor. Choose whichever method you like.

上面的状态也可以放在构造函数中。 选择您喜欢的方法。

As you can see, state in React is simply a javascript object with properties such as edit, id, and mockData. The edit property is a boolean. It will be used to show and hide the edit form to edit a particular item in mockData. The id property is used to set the id of the current item inside mockData to perform the update operation.

如您所见,React中的state只是具有诸如editidmockData之类的属性的javascript对象。 edit属性是一个布尔值。 它将用于显示和隐藏编辑表单,以编辑模拟数据中的特定项目。 id属性用于设置模拟数据中当前项目的ID,以执行更新操作。

Now that we have the mockData added to the state which is also called initial state, it’s time to add JSX. If you would like to know more about JSX, then head over for more details. It is a syntax extension to JavaScript which produces React elements to render data on pages.

现在,我们已经将嘲笑数据添加到也称为初始状态的状态 ,是时候添加JSX了。 如果您想了解有关JSX的更多信息,请以获取更多详细信息。 它是JavaScript的语法扩展,可生成React元素以在页面上呈现数据。

JSX lists all the items in mockData, that is it performs the “R” operation of CRUD. To do that, render this code to the class.

JSX列出了模拟数据中的所有项目,即它执行CRUD的“ R”操作。 为此,请将此代码呈现给类。

render() {  return (    
    {this.state.mockData.map(item => (
  • {item.title}
  • ))}
);}

The Render method is simple. First, it has the form which is used to add a new item into the todo list. This form has an onSubmit event and it calls the onSubmitHandle method which we will write later in this component.

渲染方法很简单。 首先,它具有用于将新项目添加到待办事项列表中的形式。 这种形式有一个onSubmit事件,它调用onSubmitHandle方法,我们稍后将在此组件中编写该方法。

Then we have ul and simply map through all the items inside mockData and present the title and add same buttons as in our previous examples (Delete, Edit and Complete). Now if you run your application using the “npm start” command you should see something like this.

然后,我们使用ul并简单地映射了模拟数据中的所有项,并提供了标题并添加了与前面的示例相同的按钮(删除,编辑和完成)。 现在,如果您使用“ npm start”命令运行应用程序,您应该会看到类似这样的内容。

Now that R operation is completed, it is time to add a create operation which is the C in CRUD. Add the onSubmitHandle method to the Todo Component like below.

现在,R操作完成了,是时候添加一个创建操作了,它是CRUD中的C。 将onSubmitHandle方法添加到Todo组件,如下所示。

onSubmitHandle(event) {  event.preventDefault();
this.setState({    mockData: [...this.state.mockData, {        id: Date.now(),        title: event.target.item.value,        done: false,        date: new Date()    }]  });
event.target.item.value = '';}

The onSubmitHandle method is called when the Add button is clicked. Here we use the setState method on Todo’s state which is:

单击“添加”按钮时,将调用onSubmitHandle方法。 在这里,我们在Todo的状态上使用setState方法:

setState() schedules an update to a component’s state object. When state changes, the component responds by re-rendering.

setState()计划对组件state对象的更新。 状态更改时,组件通过重新渲染进行响应。

Here, the setState method is called to reset the state of the Todo Component which has mockData. It simply appends the new item taken from the input field. Finally, set the value of the input field to empty.

在这里,调用setState方法以重置具有模拟数据的Todo组件的状态。 它只是附加从输入字段中获取的新项目。 最后,将输入字段的值设置为空。

Go ahead and refresh the app in your browser and type “Hike time” or anything you want and press the ADD button. You should be able to see the new item at the bottom of the list like above.

继续并在浏览器中刷新应用程序,然后输入“加息时间”或您想要的任何内容,然后按ADD按钮。 您应该能够在列表底部看到新的项目,如上。

Now that the C is done, it’s time for D which is Delete. Simple add the onDeleteHandle method to the Todo component like below.

既然C完成了,那么D的时候该删除了。 只需将onDeleteHandle方法添加到Todo组件中,如下所示。

onDeleteHandle() {  let id = arguments[0];
this.setState({    mockData: this.state.mockData.filter(item => {      if (item.id !== id) {        return item;      }    })  });}

This method is triggered when the delete button is clicked. As you can see, we are binding this and item.id to onDeleteHandle. The this keyword is necessary so that we have access to the current scope to access the state of the Todo Component with the this keyword, whereas the id part is used to delete that particular item.

单击删除按钮时将触发此方法。 如您所见,我们将此和item.id绑定到onDeleteHandlethis关键字是必要的,使我们有机会获得当前范围内使用this关键字来访问的Todo组件的状态,而ID部分用于删除特定项目。

In order to access the item.id, we are going to use the arguments[0] object. Once we have the id, then set the state and filter through mockData. Find the item that needs to be deleted and return all the items except the one that needs to be deleted.

为了访问item.id,我们将使用arguments [0]对象。 获得ID后,请设置状态并通过模拟数据进行过滤。 找到需要删除的项目,并返回除需要删除的项目以外的所有项目。

Go ahead and refresh your browser and press delete on the first item and you should see that it is deleted, like in the below screenshot.

继续并刷新浏览器,然后在第一项上按Delete键,您应该看到它已被删除,如下面的屏幕截图所示。

That’s all for the delete part. The Update part, as usual, consists of 2 parts. First, show the edit form when the edit button is pressed, then perform the update operation.

这就是删除部分。 与往常一样,“更新”部分由两部分组成。 首先,在按下编辑按钮时显示编辑表单,然后执行更新操作。

To show and hide the edit form, we are going to use the edit property we added to state. So add the below renderEditForm method to the component.

为了显示和隐藏编辑表单,我们将使用添加到状态的edit属性。 因此,将以下renderEditForm方法添加到组件。

renderEditForm() {    if (this.state.edit) {      return 
} }

It checks the edit state, and based on that it returns editForm which is the JSX syntax of the form.

它检查编辑状态,并根据此状态返回editForm,即表单的JSX语法。

Now call the above method in the render method inside the return keyword just above the current form, like below:

现在,在当前表单上方的return关键字内的render方法中调用上述方法,如下所示:

{this.renderEditForm()}

Now that this part is out of our way, it’s time to manipulate the edit property. Add the below onEditHandle method to the Todo Component:

既然这部分已经不合时宜了,是时候操作edit属性了。 将以下onEditHandle方法添加到Todo组件:

onEditHandle(event) {  this.setState({    edit: true,    id: arguments[0],    title: arguments[1]  });}

This method is triggered when the Edit button is pressed. We are binding three parameters: this, id, and title. The this keyword is used to reference the current component. It sets the id property to the id of the current item being edited. It sets edit to true and adds a title property to the state, which we will access later in this component.

按下“编辑”按钮时将触发此方法。 我们绑定了三个参数: thisidtitlethis关键字用于引用当前组件。 它将id属性设置为正在编辑的当前项目的id。 它将edit设置为true ,并向该状态添加title属性,我们稍后将在此组件中对其进行访问。

Now that we have this code in our component, go to the browser, refresh, and click on the edit button for the first item which will show the edit form like below:

现在,我们在组件中有了此代码,请转到浏览器,刷新,然后单击第一项的编辑按钮,这将显示如下所示的编辑表单:

This form has an input field and an update button. Now it’s time to handle the U part of CRUD. When the UPDATE button, in the edit form shown above, is pressed, the below method will be triggered:

该表单具有一个输入字段和一个更新按钮。 现在该处理CRUD的U部分了。 当按下上面显示的编辑表单中的UPDATE按钮时,将触发以下方法:

onUpdateHandle(event) {  event.preventDefault();
this.setState({      mockData: this.state.mockData.map(item => {        if (item.id === this.state.id) {          item['title'] = event.target.updatedItem.value;          return item;        }
return item;      })   });
this.setState({      edit: false   });}

Add the above method to your Todo Component. This sets the state of the component, maps through mockData inside the state, and finds the item that needs to be updated and set its title with the new title. Finally, set the edit property of the state to false to hide the form. That is it.

将上述方法添加到您的Todo组件中。 这将设置组件的状态,在状态内部映射模拟数据,并找到需要更新的项目,并使用新标题设置其标题。 最后,将状态的edit属性设置为false以隐藏表单。 这就对了。

Now run your code in your browser and try to update the first item. You should be able to see the updated title.

现在,在浏览器中运行代码,并尝试更新第一项。 您应该能够看到更新的标题。

The final method is used to set the item to a completed state. Add the below method which does exactly that.

最终方法用于将项目设置为完成状态。 添加下面的方法可以做到这一点。

onCompleteHandle() {    let id = arguments[0];
this.setState({      mockData: this.state.mockData.map(item => {        if (item.id === id) {          item['done'] = true;          return item;        }
return item;    })  });}

The above method sets he property of the item in mockData to true. This is pretty much the same as in our previous two examples in Vanilla JavaScript and Angular.

上面的方法将模仿数据中项目的属性设置为true。 这与Vanilla JavaScript和Angular中的前两个示例几乎相同。

Now to make this work, add the below code to “li” to set its class based on the “done” property state in mockData.

现在要进行此工作,将以下代码添加到“ li”,以基于模拟数据中的“完成”属性状态设置其类。

className={ item.done ? 'done' : 'hidden' }

Now refresh your browser and press the complete button. You should be able to see the below changes.

现在刷新浏览器,然后按完成按钮。 您应该能够看到以下更改。

Below is the basic CSS that needs to be added to index.css file on order to display done items on the screen.

以下是为了在屏幕上显示已完成项目而需要添加到index.css文件的基本CSS。

.done {  text-decoration: line-through;}

That is it. As you can see, Reactjs is an even more component-centric solution to modern JavaScript apps. The next task for you would be to split the form element into its own components so that we do not need to use two form elements for the update and add operations. That should be a simple and fun task for everyone.

这就对了。 如您所见,Reactjs是现代JavaScript应用程序甚至以组件为中心的解决方案。 您的下一个任务是将form元素拆分为自己的组件,这样我们就不需要为更新和添加操作使用两个form元素。 对于每个人来说,这应该是一个简单而有趣的任务。

To get the complete code, please clone the below repository.

要获取完整的代码,请克隆以下存储库。

翻译自:

react 执行入口

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

你可能感兴趣的文章
oracle 分析函数——ration_to_report 求占有率(百分比)
查看>>
面试常见
查看>>
jquery easyui+ashx+三层框架实现增删改查
查看>>
fopen,fread和fwrite
查看>>
爱的十个秘密--9.承诺的力量
查看>>
【吵架不能吵半截】
查看>>
电子书下载:Silverlight 4: Problem – Design – Solution
查看>>
为Vmware硬盘减肥瘦身
查看>>
YTT的提问以及由此引出的未来规划之思考
查看>>
QTP8.2--安装流程
查看>>
一步一步点亮Led
查看>>
POJ 3630 Phone List [Trie]
查看>>
springmvc 可以设置 <welcome-file>test.do</welcome-file>
查看>>
多Form界面控件状态变化问题分析
查看>>
面试记-(1)
查看>>
压力测试 相关
查看>>
MyBatis 通过 BATCH 批量提交
查看>>
android update automatically ( android 自动升级)
查看>>
session cookie
查看>>
POJ 1222 EXTENDED LIGHTS OUT(翻转+二维开关问题)
查看>>