懦弱什么意思| 四离日是什么意思| 为什么打雷闪电| 原本是什么意思| 七月十三日是什么日子| 杨柳木是什么生肖| 3月21是什么星座| 蓝颜知己什么意思| 农历八月十五是什么节| 斐字五行属什么| 绝世是什么意思| 角弓反张是什么意思| 为什么会有跳蚤| 冬瓜什么季节吃最好| 早孕试纸什么时候测最准确| 什么钻进风箱里两头受气| 未时右眼跳是什么预兆| 发小是什么意思| 去肝火喝什么茶| 沂字五行属什么| 晨起口干口苦是什么原因| 长痘痘涂什么药膏| 用盐水泡脚有什么好处| 经期是什么意思| iu是什么单位| 八大菜系之首是什么菜| 小米可以和什么一起煮粥| 农历7月25日是什么星座| 云南白药里的保险子有什么作用| 为什么会便血| 内脂豆腐是什么| dha宝宝什么时候吃最好| 美国什么时候建国的| 金银花洗澡对婴儿有什么好处| 疝气长在什么位置图片| 杨树林是什么牌子| 虾仁配什么蔬菜包饺子| 亮剑是什么意思| 女性排卵期是什么时候| 左脸上长痘痘是什么原因| 医院特需号是什么意思| 1963年的兔是什么命| 魔芋爽是什么做的| 地瓜什么时候成熟| 牛肉汤配什么菜好吃| 音序是什么意思| 三个手念什么| 咖啡配什么好喝| 一个王一个八念什么| prime是什么意思| 玖字五行属什么| 红花泡脚有什么好处| 相思什么意思| 脑供血不足挂什么科室| 9五行属什么| 效果图是什么意思| 大限将至什么意思| 减肥喝什么水| 文火是什么意思| 解表药是什么意思| 冬天吃什么水果| 尿检弱阳性是什么意思| 白细胞加号什么意思| 怀孕查甲功是什么意思| 路上遇到蛇是什么征兆| 鼻塞一直不好什么原因| 什么使我快乐| 4月27日是什么星座| 3p什么意思| 肾结石长什么样子图片| 右下腹有什么器官| 赤子之心什么意思| 脚心发热吃什么药| 打完狂犬疫苗不能吃什么| 胎监不过关是什么原因| 字母哥什么位置| 脚酸臭是什么原因| 女人为什么喜欢坏男人| 佳什么意思| 乳糖是什么糖| 肚脐眼下面疼是什么原因| 耻骨高是什么原因| 早泄吃什么药| 腋下长痘痘是什么原因| 左进右出有什么讲究| 天煞是什么意思| 75年属什么| 长痣是什么原因| 龟代表什么生肖| 两个虎是什么字| 肃穆是什么意思| 开理疗店需要什么证件| 梵高的星空表达了什么| 井柏然原名叫什么| 射手座是什么星象| 耷拉的近义词是什么| 肌肉损伤吃什么药| 姜汁可乐有什么功效与作用| 所以我求求你别让我离开你是什么歌| 吃什么利尿最快| 早搏吃什么药最管用| 大雪是什么意思| 错构瘤是什么病| 血红蛋白浓度偏高是什么原因| 浊是什么意思| 荏苒是什么意思| 肺部疼痛什么原因| 09属什么生肖| 反黑是什么意思| 政治面貌是什么意思| 药引子是什么意思| 喝豆浆有什么好处和坏处| 月亮象征着什么| 孕妇吃什么| 小孩肚子痛挂什么科| 张学良为什么不回大陆| 凌厉是什么意思| 麦子什么时候成熟| 女性排卵有什么症状或感觉| 西米露是什么材料做的| 停休是什么意思| 芊芊是什么意思| 印度属于什么人种| 女人吃桃子有什么好处和坏处| 女人更年期什么症状| 硬盘是什么意思| 氨咖黄敏胶囊主治什么| 什么有力| 黑舌头的狗是什么狗| 开挖掘机需要什么证| 胃热是什么原因引起的| 大生化能查出什么病来| 蜂蜜可以做什么美食| 秸秆是什么| ana医学上是什么意思| 狗有眼屎是什么原因| 为什么会梦到蛇| 什么是爱情| oa期刊是什么意思| 束带是什么| 前置胎盘需要注意什么| 什么是通勤| 黑镜讲的是什么| abby是什么意思| 早上醒来手麻是什么原因| 八是什么生肖| 喉咙有痰是什么原因| 汗臭和狐臭有什么区别怎么辨别| 为什么会有甲状腺结节| 胎盘吃了对身体有什么好处| 发低烧是什么原因| 孙子的儿子叫什么| 国五行属什么| 噬血细胞综合征是什么病| 梦见捡鸡蛋是什么意思| 额头青筋凸起是什么原因| 子宫薄是什么原因造成的| 晚上喝牛奶有什么好处| 糖耐是检查什么的| qa是什么| 包臀裙配什么上衣| 女性手麻是什么原因| 羊蝎子是什么| 悔教夫婿觅封侯是什么意思| 耳鸣是什么感觉| 为什么一紧张就想拉屎| 疣是什么意思| 男性霉菌感染用什么药| 做孕检都检查什么项目| 七月份能种什么菜| 男生生理期是什么表现| 肺实性结节是什么意思| 脾虚吃什么食物| 追求完美的人什么性格| 梦见在天上飞是什么意思| 什么名字好听| 辣椒炒什么好吃| 梦见戴帽子是什么预兆| 肥肠炖什么好吃| 学富五车是什么意思| 职称有什么用| 肾阴虚吃什么中成药| 拉倒吧是什么意思| 巧克力囊肿有什么症状表现| 出车前检查的目的是什么| 什么什么一惊| 花木兰代表什么生肖| 裘皮是什么皮| php是什么意思| 泡鲁达是什么| 鬼火是什么意思| 手上的线分别代表什么图解| 氯是什么意思| 了凡四训讲的是什么| 尿里有泡沫是什么原因| oct是什么| 胎膜早破是什么意思| 什么是脂肪瘤| 二十岁是什么之年| 二月四号是什么星座| 一什么斑点| 神经疼痛吃什么药| 海笋是什么东西| 胎儿为什么会喜欢臀位| 甲是什么意思| 十二月份的是什么星座| emoji什么意思| 女宝胶囊的作用和功效是什么| 女性脉弦是什么意思| 天蝎座是什么星座| 什么是生理期| 左脚大拇指麻木是什么原因| 房性心动过速是什么意思| 滞是什么意思| 糖醋鱼用什么鱼做好吃| 消化不良吃什么| 睁一只眼闭一只眼是什么意思| mint什么颜色| 脱氢酶高是什么原因| 鱼爱吃什么| 抓包是什么意思| 麻了是什么意思| 木石念什么| 致爱是什么意思| 无什么无什么| 检查幽门螺旋杆菌挂什么科| 合菜是什么| 如常是什么意思| 男头发稀少适合什么发型| 幽门杆菌的症状是什么| 3月1号是什么星座| 籽骨是什么意思| 体重除以身高的平方是什么指数| 什么笑容| 塞来昔布是什么药| 嫣字五行属什么| 什么叫排卵期| 边界清是什么意思| 1968年属什么生肖| 三点水翟读什么| 瘸子是什么意思| 盐酸左氧氟沙星片治什么病| 补血吃什么药最快最好| 福生无量天尊什么意思| 女人颧骨高有什么说法| 中气下陷是什么意思| 儿童肚子痛挂什么科| 什么叫体位性低血压| 活碱是什么| 红油是什么油| 当归有什么作用| 牛黄安宫丸治什么病| 男人高冷是什么意思啊| 小便黄是什么原因引起的| 抗衡是什么意思| 着床出血是什么颜色| 甲状旁腺激素高吃什么药| 输血浆主要起什么作用| epa是什么| 小壁虎的尾巴有什么作用| 抗宫炎片主要治什么| 为什么身体没力气也没有精神| 相思什么意思| 乙型肝炎表面抗原阳性是什么意思| 百度
Skip to main content

百度 "而对于未来一汽丰田发展规划,姜君表示:"除了产品和营销年轻化,未来我们也将夯实华北战略。 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

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.

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: Redux App Structure we'll examine a typical React + Redux app to see how the pieces fit together.

Starting in Part 3: Basic Redux Data Flow, 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.

How to Read This Tutorial?

This tutorial focuses on showing you how to use Redux the right way, and explains concepts along the way so that you can understand how to build Redux apps correctly.

We've tried to keep these explanations beginner-friendly, but we do need to make some assumptions about what you know already:

Prerequisites

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!

You should also make sure that you have the React and Redux DevTools extensions installed in your browser:

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 is a pattern and library for managing and updating global application state, where the UI triggers events called "actions" to describe what happened, and separate update logic called "reducers" updates the state in response. 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.

Why Should I Use Redux??

Redux helps you manage "global" state - state that is needed across many parts of your application.

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.

When Should I Use Redux??

Redux helps you deal with shared state management, but like any tool, it has tradeoffs. There are 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 is more useful when:

  • You have large amounts of application state that are needed in many places in the app
  • The app state is updated frequently over time
  • The logic to update that state may be complex
  • The app has a medium or large-sized codebase, and might be worked on by many people

Not all apps need Redux. Take some time to think about the kind of app you're building, and decide what tools would be best to help solve the problems you're working on.

Want to Know More?

If you're not sure whether Redux is a good choice for your app, these resources give some more guidance:

Redux Libraries and Tools?

Redux at its core is a small standalone JS library. It is commonly used with several other packages:

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.

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 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 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.

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:

function Counter() {
// State: a counter value
const [counter, setCounter] = useState(0)

// Action: code that causes an update to the state when something happens
const increment = () => {
setCounter(prevCounter => prevCounter + 1)
}

// View: the UI definition
return (
<div>
Value: {counter} <button onClick={increment}>Increment</button>
</div>
)
}

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

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

One-way data flow

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.

One way to solve this is to extract the shared state from the components, and put it into a centralized location outside the component tree. With this, our component tree becomes a big "view", and any component can access the state or trigger actions, no matter where they are in the tree!

By defining and separating the concepts involved in state management and enforcing rules that maintain independence between views and states, we give our code more structure and maintainability.

This is the basic idea behind Redux: a single centralized place to contain the global state in your application, and specific patterns to follow when updating that state to make the code predictable.

Immutability?

"Mutable" means "changeable". If something is "immutable", it can never be changed.

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:

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:

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')

React and Redux expect 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.

Want to Know More?

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

Terminology?

There are some important Redux terms that you'll need to be familiar with before we continue:

Actions?

An action is a plain JavaScript object that has a type field. You can think of an action as an event that describes something that happened in the application.

The type field should be a string that gives this action a descriptive name, like "todos/todoAdded". We usually write that type string like "domain/eventName", where the first part is the feature or category that this action belongs to, and the second part is the specific thing that happened.

An action object can have other fields with additional information about what happened. By convention, we put that information in a field called payload.

A typical action object might look like this:

const addTodoAction = {
type: 'todos/todoAdded',
payload: 'Buy milk'
}

Action Creators?

An action creator is a function that creates and returns an action object. We typically use these so we don't have to write the action object by hand every time:

const addTodo = text => {
return {
type: 'todos/todoAdded',
payload: text
}
}

Reducers?

A reducer is a function that receives the current state and an action object, decides how to update the state if necessary, and returns the new state: (state, action) => newState. You can think of a reducer as an event listener which handles events based on the received action (event) type.

info

"Reducer" functions get their name because they're similar to the kind of callback function you pass to the Array.reduce() method.

Reducers must always follow some specific rules:

  • They should only calculate the new state value based on the state and action arguments
  • They are not allowed to modify the existing state. Instead, they must make immutable updates, by copying the existing state and making changes to the copied values.
  • They must be "pure" - they cannot do any asynchronous logic, calculate random values, or cause other "side effects"

We'll talk more about the rules of reducers later, including why they're important and how to follow them correctly.

The logic inside reducer functions typically follows the same series of steps:

  • Check to see if the reducer cares about this action
    • If so, make a copy of the state, update the copy with new values, and return it
  • Otherwise, return the existing state unchanged

Here's a small example of a reducer, showing the steps that each reducer should follow:

const initialState = { value: 0 }

function counterReducer(state = initialState, action) {
// Check to see if the reducer cares about this action
if (action.type === 'counter/increment') {
// If so, make a copy of `state`
return {
...state,
// and update the copy with the new value
value: state.value + 1
}
}
// otherwise return the existing state unchanged
return state
}

Reducers can use any kind of logic inside to decide what the new state should be: if/else, switch, loops, and so on.

Detailed Explanation: Why Are They Called 'Reducers?'

The Array.reduce() method lets you take an array of values, process each item in the array one at a time, and return a single final result. You can think of it as "reducing the array down to one value".

Array.reduce() takes a callback function as an argument, which will be called one time for each item in the array. It takes two arguments:

  • previousResult, the value that your callback returned last time
  • currentItem, the current item in the array

The first time that the callback runs, there isn't a previousResult available, so we need to also pass in an initial value that will be used as the first previousResult.

If we wanted to add together an array of numbers to find out what the total is, we could write a reduce callback that looks like this:

const numbers = [2, 5, 8]

const addNumbers = (previousResult, currentItem) => {
console.log({ previousResult, currentItem })
return previousResult + currentItem
}

const initialValue = 0

const total = numbers.reduce(addNumbers, initialValue)
// {previousResult: 0, currentItem: 2}
// {previousResult: 2, currentItem: 5}
// {previousResult: 7, currentItem: 8}

console.log(total)
// 15

Notice that this addNumbers "reduce callback" function doesn't need to keep track of anything itself. It takes the previousResult and currentItem arguments, does something with them, and returns a new result value.

A Redux reducer function is exactly the same idea as this "reduce callback" function! It takes a "previous result" (the state), and the "current item" (the action object), decides a new state value based on those arguments, and returns that new state.

If we were to create an array of Redux actions, call reduce(), and pass in a reducer function, we'd get a final result the same way:

const actions = [
{ type: 'counter/increment' },
{ type: 'counter/increment' },
{ type: 'counter/increment' }
]

const initialState = { value: 0 }

const finalResult = actions.reduce(counterReducer, initialState)
console.log(finalResult)
// {value: 3}

We can say that Redux reducers reduce a set of actions (over time) into a single state. The difference is that with Array.reduce() it happens all at once, and with Redux, it happens over the lifetime of your running app.

Store?

The current Redux application state lives in an object called the store .

The store is created by passing in a reducer, and has a method called getState that returns the current state value:

import { configureStore } from '@reduxjs/toolkit'

const store = configureStore({ reducer: counterReducer })

console.log(store.getState())
// {value: 0}

Dispatch?

The Redux store has a method called dispatch. The only way to update the state is to call store.dispatch() and pass in an action object. The store will run its reducer function and save the new state value inside, and we can call getState() to retrieve the updated value:

store.dispatch({ type: 'counter/increment' })

console.log(store.getState())
// {value: 1}

You can think of dispatching actions as "triggering an event" in the application. Something happened, and we want the store to know about it. Reducers act like event listeners, and when they hear an action they are interested in, they update the state in response.

We typically call action creators to dispatch the right action:

const increment = () => {
return {
type: 'counter/increment'
}
}

store.dispatch(increment())

console.log(store.getState())
// {value: 2}

Selectors?

Selectors are functions that know how to extract specific pieces of information from a store state value. As an application grows bigger, this can help avoid repeating logic as different parts of the app need to read the same data:

const selectCounterValue = state => state.value

const currentValue = selectCounterValue(store.getState())
console.log(currentValue)
// 2

Redux Application Data Flow?

Earlier, we talked about "one-way data flow", which describes this sequence of steps to update the app:

  • 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

For Redux specifically, we can break these steps into more detail:

  • Initial setup:
    • A Redux store is created using a root reducer function
    • The store calls the root reducer once, and saves the return value as its initial state
    • When the UI is first rendered, UI components access the current state of the Redux store, and use that data to decide what to render. They also subscribe to any future store updates so they can know if the state has changed.
  • Updates:
    • Something happens in the app, such as a user clicking a button
    • The app code dispatches an action to the Redux store, like dispatch({type: 'counter/increment'})
    • The store runs the reducer function again with the previous state and the current action, and saves the return value as the new state
    • The store notifies all parts of the UI that are subscribed that the store has been updated
    • Each UI component that needs data from the store checks to see if the parts of the state they need have changed.
    • Each component that sees its data has changed forces a re-render with the new data, so it can update what's shown on the screen

Here's what that data flow looks like visually:

Redux data flow diagram

What You've Learned?

Redux does have a number of new terms and concepts to remember. As a reminder, here's what we just covered:

Summary
  • Redux is a library for managing global application state
    • Redux is typically used with the React-Redux library for integrating Redux and React together
    • Redux Toolkit is the standard way to write Redux logic
  • Redux's update pattern separates "what happened" from "how the state changes"
    • Actions are plain objects with a type field, and describe "what happened" in the app
    • Reducers are functions that calculate a new state value based on previous state + an action
    • A Redux store runs the root reducer whenever an action is dispatched
  • Redux uses a "one-way data flow" app structure
    • State describes the condition of the app at a point in time, and UI renders based on that state
    • When something happens in the app:
      • The UI dispatches an action
      • The store runs the reducers, and the state is updated based on what occurred
      • The store notifies the UI that the state has changed
    • The UI re-renders based on the new state

What's Next??

We've seen each of the individual pieces of a Redux app. Next, continue on to Part 2: Redux Toolkit App Structure, where we'll look at a full working example to see how the pieces fit together.

如何知道自己适合什么发型 软化灶是什么意思 山竹有什么好处 槟榔为什么那么贵 什么是阳痿
胃不好吃什么好消化又有营养 火头鱼是什么鱼 四个金读什么 guess什么意思 谦虚的什么
臻字五行属什么 脚疼是什么原因 随喜是什么意思 头一直疼是什么原因 掌眼什么意思
日本艺伎是干什么的 59是什么意思 胃火旺吃什么药 低烧是什么症状 鼻子流水是什么原因
动脉硬化有什么危害hcv9jop4ns3r.cn 谷丙转氨酶是什么hcv9jop4ns9r.cn 00年属龙的是什么命hcv9jop0ns2r.cn 06年属狗的是什么命hcv9jop4ns3r.cn 间奏是什么意思hcv9jop1ns8r.cn
二个月不来月经是什么原因hcv8jop3ns9r.cn 白细胞偏高有什么危害hcv9jop6ns6r.cn 眉毛下方有痣代表什么hcv9jop0ns7r.cn 什么什么迷人的成语hcv7jop5ns4r.cn 明天是什么日子sanhestory.com
什么屈膝hcv7jop5ns6r.cn 太监和宫女对食是什么意思hcv8jop9ns6r.cn 红肿痒是什么原因hcv8jop1ns2r.cn 什么学步hcv8jop4ns2r.cn 冰箱底部漏水是什么原因hcv8jop4ns3r.cn
秘书是什么意思hcv8jop6ns6r.cn roi是什么aiwuzhiyu.com 牡丹花有什么颜色hcv8jop8ns1r.cn 戒心是什么意思hcv8jop1ns4r.cn 闰6月是什么意思hcv8jop4ns0r.cn
百度