Redux要领,第一部分:Redux概述和概念

WHAT YOU’LL LEARN
  • What Redux is and why you might want to use it
  • Key Redux terms and concepts
  • How data flows through a Redux app

你将学到什么

  • Redux是什么和为什么你可能要用它
  • Redux主要术语和概念
  • 数据如何通过Redux应用程序流动

Introduction

Welcome to the Redux Essentials tutorial! This tutorial will introduce you to Redux and teach you how to use it the right way, using our latest recommended tools and best practices. By the time you finish, you should be able to start building your own Redux applications using the tools and patterns you’ve learned here.
欢迎来到Redux要领教程!这个教程将介绍Redux给你并教你如何正确的方式使用它,用我们最新推荐工具和最佳实践。 当你完成时,你将能使用你在这儿学到的工具和模式,构建你自己的Redux应用程序。

In Part 1 of this tutorial, we’ll cover the key concepts and terms you need to know to use Redux, and in Part 2 we’ll examine a basic React + Redux app to see how the pieces fit together.
在本教程的第一部分,我们将介绍使用Redux你需要知道的关键概念和术语,在第二部分我们将研究一个基本的React+Redux应用程序,了解各个部分如何组合在一起

Starting in Part 3, we’ll use that knowledge to build a small social media feed app with some real-world features, see how those pieces actually work in practice, and talk about some important patterns and guidelines for using Redux.
在第三部分开始,我们使用那些知识构建一个具有实际功能的小型社交媒体feed应用。看看这些片段在实际中如何工作,并讨论一些使用Redux的重要模式和指南。

How to Read This Tutorial

This page will focus on showing you how to use Redux the right way, and explain just enough of the concepts so that you can understand how to build Redux apps correctly.
**该页将侧重向你展示如何正确使用Redux,并解释足够的概念, 以便您能理解如何正确构建Redux应用程序

We’ve tried to keep these explanations beginner-friendly, but we do need to make some assumptions about what you know already:
我们尝试使这些说明适合**初学者,但我们确实需要对您已经了解的内容做出一些假设:

PREREQUISITES

前提条件

  • 熟识HTML&CSS
  • 熟识ES6语法和功能
  • 了解React术语:JSX,State,函数组件,Props,和Hooks
  • 了解异步Javascript和发出AJAX请求

If you’re not already comfortable with those topics, we encourage you to take some time to become comfortable with them first, and then come back to learn about Redux. We’ll be here when you’re ready!
如果你不熟悉这些主题,我们鼓励你花些时间先熟悉他们,然后回来学习Redux,当你准备好了,我们会在这里

You should make sure that you have the React and Redux DevTools extensions installed in your browser:
你应该确保你在你的浏览器安装了React和Redux DevTools扩展:

What is Redux?

It helps to understand what this “Redux” thing is in the first place. What does it do? What problems does it help me solve? Why would I want to use it?
首先,它有助于理解“Redux”的含义。它是做什么的?它能帮我解决什么问题?为什么我要使用它?

Redux is a pattern and library for managing and updating application state, using events called “actions”. It serves as a centralized store for state that needs to be used across your entire application, with rules ensuring that the state can only be updated in a predictable fashion.
Redux是一种管理和更新应用程序状态(state)的模式和库,使用事件调用“actions”。它作为集中状态存储服务,通过你的应用程序实例被使用,使用确保状态只能以可预测的方式更新的规则。

Why Should I Use Redux?

Redux helps you manage “global” state - state that is needed across many parts of your application.
Redux帮助你管理“全局”状态-状态在应用程序许多部分都需要。

The patterns and tools provided by Redux make it easier to understand when, where, why, and how the state in your application is being updated, and how your application logic will behave when those changes occur. Redux guides you towards writing code that is predictable and testable, which helps give you confidence that your application will work as expected.
Redux提供的模式和工具,使他更容易去理解什么时候,在哪儿,为什么和如何应用程序的状态被更新,以及当这些更改发生时你应用程序的逻辑如何表现。Redux知道你写可预期和可测试的代码,这是您有信心应用程序按预期运行。

When Should I Use Redux?

Redux helps you deal with shared state management, but like any tool, it has tradeoffs. There’s more concepts to learn, and more code to write. It also adds some indirection to your code, and asks you to follow certain restrictions. It’s a trade-off between short term and long term productivity.
Redux帮助您处理共享状态管理,但是像其他工具一样,需要权衡。有更多概念去学习,更多代码编写。它也增加了一些间接在你的代码,并要求你遵守某些限制,这是短期和长期生产率之间的权衡。

Redux Libraries and Tools

Redux is a small standalone JS library. However, it is commonly used with several other packages:
Redux是一个小型独立JS库,但是,它通常和其他几个软件包一起使用:

React-Redux

Redux can integrate with any UI framework, and is most frequently used with React. React-Redux is our official package that lets your React components interact with a Redux store by reading pieces of state and dispatching actions to update the store.
Redux可以和任意UI框架相结合,最常和React一起使用。React-Redux是我们官方包,让你的React组件和Redux相互作用,通过读状态片段和派遣action来更新store。

Redux Toolkit

Redux Toolkit is our recommended approach for writing Redux logic. It contains packages and functions that we think are essential for building a Redux app. Redux Toolkit builds in our suggested best practices, simplifies most Redux tasks, prevents common mistakes, and makes it easier to write Redux applications.
Redux工具包来编写Redux逻辑是我们推荐方法。它包含构建Redux应用程序所必须的软件包和函数。Redux Toolkit 构建是我们建议的最佳实践,简化大多数Redux任务,防止常见错误,并简化编写Redux应用程序的过程。

Redux DevTools Extension

The Redux DevTools Extension shows a history of the changes to the state in your Redux store over time. This allows you to debug your applications effectively, including using powerful techniques like “time-travel debugging”.
Redux DevTools Extension 展示在Redux存储中的状态更改的历史记录。这使你可以有效地调试你的应用程序,包括使用强大的技术,像“时间旅行调试”。
**

Redux Terms and Concepts

Before we dive into some actual code, let’s talk about some of the terms and concepts you’ll need to know to use Redux.
在我们深入一些实际代码之前,讨论一些你在使用Redux时需要知道术语和概念。

State Management

Let’s start by looking at a small React counter component. It tracks a number in component state, and increments the number when a button is clicked:
首先看一个小的React计数器组件,追踪组件状态下的一个数字,当按钮被点击时增加数字:

  1. function Counter() {
  2. // State: a counter value
  3. const [counter, setCounter] = useState(0)
  4. // Action: code that causes an update to the state when something happens
  5. const increment = () => {
  6. setCounter(prevCounter => prevCounter + 1)
  7. }
  8. // View: the UI definition
  9. return (
  10. <div>
  11. Value: {counter} <button onClick={increment}>Increment</button>
  12. </div>
  13. )
  14. }

It is a self-contained app with the following parts:

  • The state, the source of truth that drives our app;
  • The view, a declarative description of the UI based on the current state
  • The actions, the events that occur in the app based on user input, and trigger updates in the state

这是一个包含以下部分的自包含程序:

  • 状态:驱动应用程序的真理之源;
  • 视图:基于当前状态的UI声明式描述
  • action : 根据用户输入在应用程序中发生事件,并触发状态更新

This is a small example of “one-way data flow”:

  • State describes the condition of the app at a specific point in time
  • The UI is rendered based on that state
  • When something happens (such as a user clicking a button), the state is updated based on what occurred
  • The UI re-renders based on the new state

这是一个“单向数据流”的小案例:

  • 状态描述了特定时间点的应用状态
  • UI根据状态被渲染
  • 当某事发生(比如用户点击按钮),根据发生的情况更新状态
  • UI根据新状态重新渲染


one-way-data-flow.png**
However, the simplicity can break down when we have multiple components that need to share and use the same state, especially if those components are located in different parts of the application. Sometimes this can be solved by “lifting state up” to parent components, but that doesn’t always help.

Immutability

“Mutable” means “changeable”. If something is “immutable”, it can never be changed.
“Mutable”意思是“可变的”。如果某事是“immutable”,它不能被改变。

JavaScript objects and arrays are all mutable by default. If I create an object, I can change the contents of its fields. If I create an array, I can change the contents as well:
JavaScript对象和数组默认都是可变的。如果我创建了一个对象,我能更改它字段的内容。如果创建一个数组,我也能更改内容:

const obj = { a: 1, b: 2 }
// still the same object outside, but the contents have changed
obj.b = 3

const arr = ['a', 'b']
// In the same way, we can change the contents of this array
arr.push('c')
arr[1] = 'd'

This is called mutating _the object or array. It’s the same object or array reference in memory, but now the contents inside the object have changed.
这称为使对象或者数组变异。它与内存中的对象或者数组引用相同,但现在对象的内容已经更改。

In order to update values immutably, your code must make _copies
of existing objects/arrays, and then modify the copies.
为了更新不可变的值,你的代码必须制作对象或数组的副本,然后修改副本。

We can do this by hand using JavaScript’s array / object spread operators, as well as array methods that return new copies of the array instead of mutating the original array:
我们用Javascript的数组/对象散布运算符手动完成此操作,以及返回数组新副本而不是改变原始数组的数组方法:

const obj = {
  a: {
    // To safely update obj.a.c, we have to copy each piece
    c: 3
  },
  b: 2
}

const obj2 = {
  // copy obj
  ...obj,
  // overwrite a
  a: {
    // copy obj.a
    ...obj.a,
    // overwrite c
    c: 42
  }
}

const arr = ['a', 'b']
// Create a new copy of arr, with "c" appended to the end
const arr2 = arr.concat('c')

// or, we can make a copy of the original array:
const arr3 = arr.slice()
// and mutate the copy:
arr3.push('c')

Redux expects that all state updates are done immutably. We’ll look at where and how this is important a bit later, as well as some easier ways to write immutable update logic.
Redux期望所有数据更新都是immutably. 稍后,我们将探讨何处和如何变重要,以及更容易的方式书写immutable更新逻辑。

WANT TO KNOW MORE?

For more info on how immutability works in JavaScript, see:

想知道更多? 更多信息关于在javascript中不可变更如何工作,如下:

**

Terminology

There’s some important Redux terms that you’ll need to be familiar with before we continue:
在我们开始之前你有一些需要熟悉的重要Redux术语 :

Actions

Action Creators

Reducers

StoreDispatch

Dispatch

Selectors

Redux Application Data Flow