博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
react-hooks_使用React Hooks构建一个React To-Do应用(无类组件)
阅读量:2511 次
发布时间:2019-05-11

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

react-hooks

Yes, a to-do app, seems like something we’ve all done in the past. The great thing about a to-do app is that it covers all 4 aspects of CRUD; Create, Read, Update, Delete. As a developer, we need to know CRUD and a to-do app is the best way to start that learning or refresh some of the things we may be a little rusty on.

是的,一个待办事项应用程序,似乎就像我们过去所做的一样。 待办事项应用程序的妙处在于它涵盖了CRUD的所有4个方面; 创建,读取,更新,删除。 作为开发人员,我们需要了解CRUD,而待办事项应用程序是开始学习或刷新我们可能会有些生锈的事情的最佳方式。

is the frontend JavaScript library we are going to be using today. Whether you are new to React or are an avid React user, we can all agree on one thing: React is pretty great.

是我们今天将要使用的前端JavaScript库。 无论您是React的新手还是React的狂热用户,我们都可以达成共识: React很棒

We've already done a here at Scotch, but that was with Class components. Today we will have no Class components by integrating , React’s newest . Let’s get started.

我们已经在Scotch上完成了一个 ,但这是使用Class组件完成的。 今天,通过集成React的最新 ,我们将没有Class组件 。 让我们开始吧。

影片教学 (Video Tutorial)

For a video version of this tutorial, check out :

有关本教程的视频版本,请查看 :

( )

React is always improving and growing. The latest update is React 16.7, so new it’s in alpha stages. In this upgrade, we are given the power of React Hooks.

React一直在进步并在成长。 最新的更新是React 16.7,所以新的版本处于alpha阶段。 在此升级中,我们获得了React Hooks的强大功能。

React Hooks allow for functional components to have a state and utilize lifecycle methods.

React Hook允许功能组件具有状态并利用生命周期方法。

No longer do we need to rely on just class components for that functionality.

我们不再需要仅依靠类组件来实现该功能。

You can learn all about or visit .

您可以了解有关全部信息或访问 。

( )

Navigate to the place you would like your new application to be located and type:

导航到您希望新应用程序位于的位置,然后键入:

npx create-react-app react-to-do

*Note: *Running npxbefore the command allows for it to be installed if it is not already installed globally on your machine.

* 注意:*如果尚未在计算机上全局安装npx ,请在命令之前运行npx

Sit back and relax, React is taking care of the initial build for your new application.

坐下来放松,React正在照顾您新应用程序的初始构建。

Once it is done, you will need to navigate into the project:

完成后,您将需要导航到项目:

cd react-to-do

and then to run the project:

然后运行项目:

npm run start

and navigate to http://localhost:3000/ to see the spinning React logo in your browser.

并浏览至http://localhost:3000/以在浏览器中查看旋转的React徽标。

目前在Alpha中React16.7 (React 16.7 currently in alpha)

At the time of this writing, React Hooks are in React 16.7, but React 16.7 is in alpha currently. You'll need to install that specifically until it comes out of alpha.

在撰写本文时,React Hooks在React 16.7中,但是React 16.7当前在alpha中。 您需要专门安装它,直到它脱离alpha版本为止。

npm install -S react@16.7.0-alpha.2 react-dom@16.7.0-alpha.2

使用CodeSandbox (Using CodeSandbox)

CodeSandbox is a great tool to build applications in your browser without having to open up your CLI. Try building this online. Also, be sure to remove the React 16.6 dependencies and add React 16.7.

CodeSandbox是一个很好的工具,无需打开CLI即可在浏览器中构建应用程序。 尝试在线构建它。 另外,请确保删除React 16.6依赖项并添加React 16.7。

( )

Jump into your src/App.css file and add in the three classes we will be using throughout our app. Styling won't be the focus of this app, so we'll keep this short and sweet.

跳到src / App.css文件,并添加我们将在整个应用程序中使用的三个类。 样式将不是此应用程序的重点,因此我们将使其简短而优美。

src / App.css (src/App.css)

.app {
background: #209cee; padding: 30px; height: 100vh;}.todo-list {
background: #e8e8e8; border-radius: 4px; padding: 5px; max-width: 400px;}.todo {
background: #fff; box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.15); padding: 3px 10px; font-size: 12px; margin-bottom: 6px; border-radius: 3px; display: flex; align-items: center; justify-content: space-between;}

( )

With your application running and the styling ready to be used, let’s start on the Read part of CRUD. We’ll want to make a list of things, just so we can Read/view the list.

运行您的应用程序并准备使用样式后,让我们从CRUD的“读取”部分开始。 我们将要列出一个事物列表,以便我们可以阅读/查看该列表。

增加状态 (Adding in State)

Go into your src/App.js file and let’s add a state to our component. We are going to be using React Hooks so state will look a little different than what you're used to in classes.

进入src/App.js文件,让我们向组件添加状态。 我们将使用React Hooks,因此状态看起来与您在类中的习惯有所不同。

src / App.js (src/App.js)

function App() {
const [todos, setTodos] = useState([ {
text: "Learn about React" }, {
text: "Meet friend for lunch" }, {
text: "Build really cool todo app" } ]); // we'll render our todos here ... // return
}

The component, as we can see, is a functional component. In past versions of React, function components were unable to handle state, but now, by using Hooks, they can.

如我们所见,该组件是功能组件。 在过去的React版本中,功能组件无法处理状态,但是现在,通过使用Hooks,它们可以处理状态。

  • The first parameter, todos is what we are going to name our state.

    第一个参数, todos是我们要命名的州。
  • The second parameter, setTodos is what we are going to use to set the state.

    第二个参数setTodos是我们将用来设置状态的参数。

We've got a writeup on array destructuring if you want to know more info about that [todos, setTodos] syntax .

如果您想在了解有关[todos, setTodos]语法的更多信息[todos, setTodos]数组解构。

The hook of useState is what React uses to "hook" into the state or lifecycle of the component. We then create an array of objects and we have the beginnings of our state.

useState的挂钩是React用于“挂钩”组件的状态或生命周期的挂钩。 然后,我们创建对象的数组,并从状态开始。

与类组件比较 (Comparing to a Class Component)

Let's take a quick detour and see how this would've done with classes:

让我们快速绕道,看看如何对类进行处理:

class App extends Component {
state = {
todos: [ {
text: "Learn about React" }, {
text: "Meet friend for lunch" }, {
text: "Build really cool todo app" } ] } setTodos = todos => this.setState({
todos }); render() {
return
}}

A lot more typing. React Hooks let's us make that really clean! We'll continue with our functional component version from above.

还有很多打字。 React Hooks让我们让它变得真正干净! 我们将从上面继续我们的功能组件版本。

我们的“ Todo”组件 (Our "Todo" Component)

We will want to create a component that we can use later on in the return of the main App component. We will call that Todo and it will pass in the (todo) and show the “text” part of the todo (todo.text), like so:

我们将要创建一个组件,稍后在返回主App组件时可以使用。 我们将其称为Todo ,它将传入( todo )并显示todo的“文本”部分( todo.text ),如下所示:

const Todo = ({
todo }) =>
{
todo.text}
;

Let’s see how we will use that in our App component.

让我们看看如何在App组件中使用它。

使用我们的Todo变量获取返回的列表 (Using Our Todo Variable to Get a List Returned)

Go down to the return part of the App component and remove almost everything. We want to empty out that return part especially so that the spinning logo we saw earlier when we navigated to http://localhost:3000, goes away and we have our list being displayed on the page.

转到App组件的return部分,并删除几乎所有内容。 我们要特别清空返回部分,以使我们之前导航到http://localhost:3000时看到的旋转徽标消失,并且列表显示在页面上。

By using the , we are able to create a new array of items by mapping over the todo items from state and displaying them by index.

通过使用 ,我们可以通过映射状态中的todo并按索引显示它们来创建新的项目数组。

Let’s create a pretty list of items:

让我们创建一个漂亮的项目列表:

src / App.js (src/App.js)

return (    
{
todos.map((todo, index) => (
))}
);

Navigate to your browser and you should see something like this:

导航到浏览器,您应该看到类似以下内容的内容:

( )

Want to create a new item to the list? What if we forgot to add something to our to-do list and don’t want to forget that thing? Let’s give our application the power to Create a new item for our to-do app.

是否要在列表中创建一个新项目? 如果我们忘记将某些事情添加到待办事项列表中,又不想忘记那件事怎么办? 让我们让应用程序能够为待办事项应用程序创建一个新项目。

While in the src/App.js file, we are going to want to add a couple of things. At the top we are going to add another component, we’ll call it TodoForm. In this component we want it to:

src/App.js文件中时,我们将要添加一些内容。 在顶部,我们将添加另一个组件,我们将其TodoForm 。 在此组件中,我们希望它:

  • Start with an empty state for an input field.

    从输入字段的空状态开始。
  • Be able to update the form by setting the state.

    能够通过设置状态来更新表单。
  • Handle the submit.

    处理提交。

设置表单输入的空状态 (Setting our Empty State for the Form Input)

Remember, we are using React Hooks so state is going to be a little different. To set our state we are going to want to write it like so:

记住,我们使用的是React Hooks,所以状态会有所不同。 要设置状态,我们将要这样写:

const [value, setValue] = useState("");

The first is the "value" and the second is how we are going to be setting the state. The state starts off empty and as we add things to our state, it will add it to our list of to-do items.

第一个是“值”,第二个是我们将如何设置状态。 状态开始时是空的,当我们在状态中添加内容时,会将其添加到待办事项列表中。

We will want to add in a handleSubmit variable that can handle our addTodo function (we will make that function soon) and add the item to the list. If nothing is in the input box and the user presses “enter”, we want it to not do anything (i.e., not add in an empty tile to the list).

我们将要添加一个handleSubmit变量,该变量可以处理我们的addTodo函数(我们将很快制作该函数)并将该项目添加到列表中。 如果输入框中没有任何内容,并且用户按下“输入”,我们希望它什么也不做(即,不要在列表中添加空白图块)。

Adding that functionality into a form that has an input box, we should have our code look like this:

将该功能添加到具有输入框的表单中,我们应该使代码如下所示:

src / App.js (src/App.js)

function TodoForm({
addTodo }) {
const [value, setValue] = useState(""); const handleSubmit = e => {
e.preventDefault(); if (!value) return; addTodo(value); setValue(""); }; return (
setValue(e.target.value)} />
);}

The addTodo function I told you about earlier? Let’s go ahead and build that now. Staying within App.js, under the state of the App component, the function should be able to grab the existing list of items, add on the new item, and display that new list.

我之前告诉过您的addTodo函数? 让我们继续构建它。 App.jsApp.js ,在App组件的状态下,该功能应能够获取现有项目列表,添加新项目并显示该新列表。

src / App.js (src/App.js)

const addTodo = text => {
const newTodos = [...todos, {
text }]; setTodos(newTodos); };

Notice the lack of this.state.? With the new React Hooks, we have no more need to use that. Can you use it? Sure, of course. But the new Hooks allow for less typing, more efficiency, and understand that this.state. is going to be implied in certain places.

注意缺少this.state. ? 使用新的React Hooks,我们不再需要使用它。 可以使用吗? 当然可以。 但是新的Hooks允许更少的键入,更高的效率,并且了解this.state. 在某些地方将被暗示。

See that ? The three dots before the todos, that is essentially "copying" the list for us so that we are able to add on the new to-do item. Then using our keyword that we set earlier, we will set the state with setTodos.

看到那个点吗? todos之前的三个点,实际上是为我们“复制”列表,以便我们可以添加新的待办事项。 然后使用我们之前设置的关键字,使用setTodos设置状态。

By using the TodoForm down in the return of the App component, we will see that input box pop up now. The entire src/App.js file should look like this so far:

通过在App组件的返回中向下使用TodoForm ,我们将看到现在弹出输入框。 src/App.js ,整个src/App.js文件应如下所示:

src / App.js (src/App.js)

import React, {
useState } from "react";import "./App.css";const Todo = ({
todo }) =>
{
todo.text}
;function TodoForm({
addTodo }) {
const [value, setValue] = useState(""); const handleSubmit = e => {
e.preventDefault(); if (!value) return; addTodo(value); setValue(""); }; return (
setValue(e.target.value)} />
);}function App() {
const [todos, setTodos] = useState([ {
text: "Learn about React" }, {
text: "Meet friend for lunch" }, {
text: "Build really cool todo app" } ]); const addTodo = text => {
const newTodos = [...todos, {
text }]; setTodos(newTodos); }; return (
{
todos.map((todo, index) => (
))}
);} export default App;

Go to your browser and play around. You can now add in a to-do item to your list!

转到浏览器并播放。 现在,您可以将待办事项添加到列表中!

( )

How would we want to update our to-do application? Maybe let’s have the functionality of being able to cross off an item. Let’s get started on that code!

我们将如何更新待办事项应用程序? 也许让我们拥有能够划掉一个项目的功能。 让我们开始编写该代码!

更新我们的国家 (Updating our State)

Our state in our App component needs a little extra to it for the "Completed" status to be able to change. We will be adding in another key/value pair to our list of objects. By adding in an "isCompleted: false" value, we set that to false to begin with and will, when prompted, change that to true.

我们在App组件中的状态需要一些额外的内容,才能更改“已完成”状态。 我们将在我们的对象列表中添加另一个键/值对。 通过添加“ isCompleted:false”值,我们将其设置为false开头,并在出现提示时将其更改为true。

src / App.js (src/App.js)

const [todos, setTodos] = useState([     {
text: "Learn about React", isCompleted: false }, {
text: "Meet friend for lunch", isCompleted: false }, {
text: "Build really cool todo app", isCompleted: false } ]);

We will need a function like the addTodo function but this one will be able to “complete” an item. We will want to do some similar things that we did in the addTodo like using the spread operator to grab the current list of items. In this function, we will be changing the isCompleted status to true so that it knows it has been completed. It will then update the state and set the state to the newTodos.

我们将需要一个类似于addTodo函数的函数,但是该函数将能够“完成”一项。 我们将要做一些与addTodo类似的事情,例如使用传播操作符来获取当前项列表。 在此函数中,我们将isCompleted状态更改为true ,以使其知道已完成。 然后它将更新状态并将状态设置为newTodos

src / App.js (src/App.js)

const completeTodo = index => {
const newTodos = [...todos]; newTodos[index].isCompleted = true; setTodos(newTodos); };

By using completeTodo in the Todo function, we are going to be able to fire off that functionality. When the “Complete” button is clicked, it will add in the textDecoration styling and cross-out the item. We are using a , a feature within ES6 JavaScript, which is a simpler way of doing an if/else statement. This is our way of completing an item on the list and “updating” the list. The code should look as follows:

通过在Todo函数中使用completeTodo ,我们将能够启动该功能。 单击“完成”按钮后,它将添加到textDecoration样式中并划掉该项。 我们正在使用 ,这是ES6 JavaScript中的一项功能,这是执行if/else语句的一种更简单的方法。 这是我们完成列表中的项目并“更新”列表的方式。 该代码应如下所示:

src / App.js (src/App.js)

function Todo({
todo, index, completeTodo }) {
return (
{
todo.text}
);}

Dive down to the return of the App component and we’ll add in the following line:

深入研究App组件的return ,然后添加以下行:

completeTodo={
completeTodo}

to look like this in the code:

在代码中看起来像这样:

src / App.js (src/App.js)

{
todos.map((todo, index) => (
))}

Returning to the browser, your to-do app should look something like this when a “Complete” button is clicked.

返回浏览器,当您单击“完成”按钮时,您的待办应用程序应如下所示。

Now we can read our list, add to our list, and update the completed status of each item. What’s left? Delete an item.

现在,我们可以阅读列表,添加到列表中,并更新每个项目的完成状态。 还剩下什么? 删除项目。

( )

So you’ve completed an item on your to-do list, the day is over and you want to delete it from your list to be able to start over tomorrow. We are going to want to delete that item completely. Let’s see how we can get that going.

因此,您已经完成了待办事项清单上的一个项目,这一天结束了,您希望将其从清单中删除,以便明天开始。 我们将要完全删除该项目。 让我们看看如何实现这一目标。

By adding just a couple lines, we will be able to add in the functionality of deleting an item.

通过仅添加几行,我们将能够添加删除项的功能。

We will go ahead and build the removeTodo function so that when we click on an “X” to delete an item, that will be fired off. That function will be located by the others underneath the state of the App component.

我们将继续构建removeTodo函数,以便当我们单击“ X”以删除项目时,将其触发。 该功能将由其他功能定位在App组件的状态下。

In this removeTodo function, we will again be using the spread operator but once we grab that current list, we will be "" the chosen index off of the array of items. Once that is removed, we will return the new state by setting it with setTodos to be newTodos.

在这个removeTodo函数中,我们将再次使用散布运算符,但是一旦我们获取了当前列表,就将“选择”的索引从项目数组中“ ”出来。 一旦被删除,我们将通过设置它返回的新状态setTodosnewTodos

src / App.js (src/App.js)

const removeTodo = index => {
const newTodos = [...todos]; newTodos.splice(index, 1); setTodos(newTodos); };

In your Todo function, you will want to add in this line:

在您的Todo函数中,您需要添加以下行:

like this:

像这样:

src / App.js (src/App.js)

function Todo({
todo, index, completeTodo, removeTodo }) {
return (
{
todo.text}
);}

You’ll see as well that we are bringing in removeTodo at the top and then using it in the onClick of the “X”.

removeTodo看到,我们在顶部引入了removeTodo ,然后在“ X”的onClick中使用它。

Adding in the removeTodo in the Todo part of the returning the App component, our “delete” will be fully functional. Add it in here:

在返回的App组件的Todo部分中添加removeTodo ,我们的“删除”功能将完全可用。 在这里添加:

src / App.js (src/App.js)

With that added in, go to your browser and you’ll see a button with an "X" that when clicked, deletes the item completely.

添加该内容后,转到浏览器,您将看到带有“ X”的按钮,单击该按钮将完全删除该项目。

( )

The entire src/App.js file should look like this in the end:

最后,整个src/App.js文件应如下所示:

src / App.js (src/App.js)

import React, {
useState } from "react";import "./App.css";function Todo({
todo, index, completeTodo, removeTodo }) {
return (
{
todo.text}
);}function TodoForm({
addTodo }) {
const [value, setValue] = useState(""); const handleSubmit = e => {
e.preventDefault(); if (!value) return; addTodo(value); setValue(""); }; return (
setValue(e.target.value)} />
);}function App() {
const [todos, setTodos] = useState([ {
text: "Learn about React", isCompleted: false }, {
text: "Meet friend for lunch", isCompleted: false }, {
text: "Build really cool todo app", isCompleted: false } ]); const addTodo = text => {
const newTodos = [...todos, {
text }]; setTodos(newTodos); }; const completeTodo = index => {
const newTodos = [...todos]; newTodos[index].isCompleted = true; setTodos(newTodos); }; const removeTodo = index => {
const newTodos = [...todos]; newTodos.splice(index, 1); setTodos(newTodos); }; return (
{
todos.map((todo, index) => (
))}
);}export default App;

( )

A to-do app can be a great reminder or starting point when it comes to CRUD in web development. Being able to read information, create new information, update existing information, and deleting said information can be powerful in any application.

待办事项应用程序可能是Web开发中CRUD的重要提醒或起点。 在任何应用程序中,能够读取信息,创建新信息,更新现有信息以及删除所述信息都是很强大的。

are great. They allow for a more straight-forward way of coding and can make your code clear and concise.

很棒。 它们允许使用更直接的编码方式,并使您的代码清晰明了。

Now go have fun adding all your many to-do items to your newly built to-do app. And then have even more fun crossing them off when you finish them!

现在开始玩乐,将您的许多待办事项添加到新建的待办应用中。 然后,当您完成这些任务时,将它们交织起来会带来更多的乐趣!

Happy coding!

编码愉快!

翻译自:

react-hooks

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

你可能感兴趣的文章
PHP Curl发送数据
查看>>
HTTP协议
查看>>
HTTPS
查看>>
git add . git add -u git add -A区别
查看>>
apache下虚拟域名配置
查看>>
session和cookie区别与联系
查看>>
CentOS7 重置root密码
查看>>
Centos安装Python3
查看>>
PHP批量插入
查看>>
laravel连接sql server 2008
查看>>
Laravel框架学习笔记之任务调度(定时任务)
查看>>
浅析 Laravel 官方文档推荐的 Nginx 配置
查看>>
Swagger在Laravel项目中的使用
查看>>
Laravel 的生命周期
查看>>
Nginx
查看>>
Navicat远程连接云主机数据库
查看>>
Nginx配置文件nginx.conf中文详解(总结)
查看>>
【2020-3-21】Mac安装Homebrew慢,解决办法
查看>>
influxdb 命令行输出时间为 yyyy-MM-dd HH:mm:ss(年月日时分秒)的方法
查看>>
jxl写入excel实现数据导出功能
查看>>