通过达斯·维达(Darth Vader)的叛军追捕来解释React道具/状态

by Kevin Kononenko

凯文·科诺年科(Kevin Kononenko)

通过达斯·维达(Darth Vader)的叛军追捕来解释React道具/状态 (React Props/State Explained Through Darth Vader’s Hunt for the Rebels)

如果您看过《星球大战》,那么您可以了解道具和状态。 (If you’ve seen Star Wars, then you can understand props and state.)

Props and state are essential to writing readable React code. But they’re hard concepts to grasp, because they’re based around an entirely different paradigm than Angular or jQuery (if you have used either of those).

道具和状态对于编写可读的React代码至关重要。 但是它们是很难理解的概念,因为它们所基于的范式与Angular或jQuery(如果您曾经使用过两者)完全不同。

But don’t worry — I’m going to clear everything up with a Star Wars analogy.

但请放心,我将以《星球大战》的类比来澄清一切。

That’s right. If you’ve seen the original Star Wars series, you can understand props and state.

那就对了。 如果您看过原始的《星球大战》系列,则可以了解道具和状态。

Here’s a spoiler-free refresher of the basic premise of episodes 4–6:

这是第4-6集的基本前提的无扰动复习:

  1. Darth Vader hunts the rebels relentlessly, as they are the last resistance against the Galactic Empire.

    达斯·维达(Darth Vader)不懈地追捕叛乱分子,因为他们是对银河帝国的最后抵抗。
  2. The rebels, led by Princess Leia and Luke Skywalker, must fight back and exploit vulnerabilities within the Empire.

    由莱娅公主和卢克·天行者领导的叛军必须进行反击并利用帝国内部的脆弱性。
  3. Darth Vader uses a variety of tactics to try and discover the movements of the rebels, including an army of Stormtroopers, a fleet of starships, and a variety of scouts.

    达斯·维达(Darth Vader)使用多种策略来尝试发现叛军的行动,包括一支突击队,一支飞船舰队和各种侦察兵。

The entire plan for the Empire’s resources depends upon Vader’s leadership.

帝国资源的整个计划取决于维达的领导。

If you are used to using jQuery, you may think about creating one event handler (like a click() handler), then explicitly changing different parts of the user interface line-by-line.

如果您习惯使用jQuery,则可以考虑创建一个事件处理程序(如click()处理程序),然后逐行显式更改用户界面的不同部分。

But in React, the idea is that when state is modified, the changes will automatically trickle down to all child components via props. So you only need to write the code to change one thing — the state and watch as your UI updates.

但是在React中,想法是修改状态后,更改将通过props 自动滴入所有子组件。 因此,您只需要编写代码来更改一件事- 状态 - 并观看您的UI更新。

This is similar to the way that Darth Vader commands the three wings of his army. Once word gets back to him of the rebel location, his resources will automatically mobilize to launch an attack.

这类似于达斯·维达(Darth Vader)指挥其军队的三个联队的方式。 一旦有消息告诉他叛军所在地,他的资源将自动动员起来发动进攻。

Let’s get into it. This tutorial will require a basic knowledge of JSX, which you can learn more about here.

让我们开始吧。 本教程将需要JSX的基本知识,您可以在此处了解更多信息。

银河帝国概述 (A Summary of The Galactic Empire)

Here are the three wings of the Galactic Empire.

这是银河帝国的三翼。

The Imperial Army is composed of Stormtroopers, AT-ATs, AT-STs and others.

帝国军由突击队,AT-AT,AT-ST等组成。

The Imperial Navy is composed of star destroyers, TIE fighters and others.

帝国海军由星际驱逐舰,TIE战斗机等组成。

Military Intelligence is composed of bounty hunters like Boba Fett, probe droids, and any other specialized scouts.

军事情报包括赏金猎人,如Boba Fett,探测机器人和任何其他专业侦察员。

Here is a quick org chart that will give some direction on how we will write our components.

这是一个快速的组织结构图,它将为我们如何编写组件提供一些指导。

A reminder: Vader’s first goal is to find the location of the rebels. Those at the bottom of the org chart are the actual functional units that can accomplish this. If one of them finds a rebel base, their instructions would be to return to Vader so that he could execute his battle plans.

提醒:维达的第一个目标是找到叛军的所在地。 组织结构图底部的那些是可以实现此目的的实际功能单元。 如果其中之一找到了叛军基地,他们的指示将是返回维达,以便他执行其作战计划。

React is all about dynamic user interface. When a user completes a specific action, how does state change? In this case, Darth Vader would have a state called rebelLocation. Since that is the key dynamic variable, the three wings of the Empire would mobilize due to a change in the rebelLocation state.

React是关于动态用户界面的 。 用户完成特定操作后, 状态如何变化? 在这种情况下,达斯·维达(Darth Vader)将拥有一个名为rebelLocation状态 。 由于这是关键的动态变量,因此由于rebelLocation 状态的变化,帝国的三个分支将动员起来。

Stormtrooper encounters rebel base → Return to Darth Vader with location

冲锋队遇到叛军基地→返回达斯·维达

User clicks certain element → Update the state of some parent component

用户单击某些元素→更新某些父组件的状态

Here are the basics in code, which follows the org chart above:

以下是代码的基础知识,它们遵循上面的组织结构图:

国家解释 (State Explained)

State allows you to dynamically change many elements at once based on one variable. State encompasses the key parts of your UI that change basic on user input.

状态允许您基于一个变量一次动态地更改许多元素。 状态包含UI的关键部分,这些关键部分会根据用户输入而更改。

With less things to keep track of in state, you will be able to write components with more clarity and fewer opportunities for bugs. When state changes, many components may change in accordance based on the one variable.

使用更少的东西来跟踪状态,您将能够更加清晰地编写组件,并且减少错误的机会。 当状态发生变化时,许多组件可能会根据一个变量发生变化。

jQuery approaches this by asking you to write one line for every element that must be changed. It is not explicitly based on the parent-child relationship like state is.

jQuery通过要求您为必须更改的每个元素写一行来解决这一问题。 它不是像状态一样显式地基于父子关系。

Let’s say Stormtroopers encounter the rebels. Vader has ordered them to report to him as soon as possible. Once they return with a rebel location, Vader can carry out the rest of his orders, which were contingent on the rebel location. Here is a modified diagram that charts the path through the components listed above.

假设突击队遇到叛军。 维达已命令他们尽快向他报告。 一旦他们回到叛军所在地,维达就可以执行他的其余命令,这些命令视叛军所在地而定。 这是一个修改后的图,它绘制了通过上面列出的组件的路径。

Orders are already passed down to every member at the bottom of the chart. Once they run into rebels, they know to return to Lord Vader. The rebelLocation state will then be updated with the planet, be it “Endor”, “Hoth”, or somewhere else.

订单已经向下传递到图表底部的每个成员。 一旦遇到叛乱分子,他们便知道要返回维德勋爵。 然后, rebelLocation状态将随行星更新,无论是“ Endor”,“ Hoth”还是其他位置。

This is the same concept as receiving user input then updating state in a parent component. Many React practitioners choose to write components with a singular function, so the component that actually listens for the user input will almost always be different than the component that holds state.

这与接收用户输入然后在父组件中更新状态的概念相同。 许多React从业者选择编写具有单一功能的组件,因此实际监听用户输入的组件几乎总是与保持状态的组件不同。

Above: Stormtrooper nested within ImperialArmy nested within vadersEmpire

上图:突击队嵌套在帝国军中,陆军嵌套在vadersEmpire中

In a real app: User input nested within parent div nested within parent div

在实际应用中:嵌套在父div中的用户输入嵌套在父div中的用户输入

状态改变时会发生什么? (What happens when state changes?)

This is the beauty of React. Rather than writing complicated event handlers (like in jQuery), everything is contingent upon changes in state. You can clearly trace changes in the UI to these state changes.

这就是React的美。 而不是编写复杂的事件处理程序(例如在jQuery中),一切都取决于状态的变化。 您可以清楚地将UI中的更改跟踪到这些状态更改。

In this case, once the rebelLocation is discovered, the state would change to that planet. But that is only half the story. Darth Vader would have plans in mind to mobilize different assets based on this state change. He can prepare them in advance for this possibility. As in, “When we find their planet, travel there immediately and prepare for an assault!”

在这种情况下,一旦找到rebelLocation状态就会更改为该星球。 但这仅仅是故事的一半。 达斯·维达(Darth Vader)会考虑基于此状态变化动员不同资产的计划。 他可以为这种可能性提前做好准备。 就像“当我们找到他们的星球时,立即前往那里准备袭击!”

Once state changes, the changes are automatically shared with all 3 wings of the Empire. Similarly, when the state of a parent component changes, the child components automatically inherit the new state.

状态更改后,更改将自动与帝国的所有3个分支共享。 同样,当父组件的状态更改时,子组件会自动继承新状态。

Every component can also have its own state. For example, the ImperialArmy component might have a troopsCount state which counts the members of the army. We will not modify that in this example, but you can imagine that a battle might affect troopsCount.

每个组件也可以有自己的状态。 例如, ImperialArmy组件可能具有一个部队计数状态,该状态对部队成员进行计数。 在本示例中,我们将不会对此进行修改,但是您可以想象一场战斗可能会影响ArmyCount

Notice how this state does not depend on rebelLocation. If it did, we would not want to explicitly declare another state. We would want it to automatically update based on a change in rebelLocation state.

请注意,此状态如何不依赖于rebelLocation 。 如果确实如此,我们将不想显式声明另一个状态。 我们希望它根据rebelLocation状态的变化自动更新。

Since it is independent, here is what the code looks like:

由于它是独立的,因此代码如下所示:

Wait, so how does this state get communicated between the different components? That brings us to… props!

等待,那么如何在不同组件之间传达这种状态? 那把我们带到了……道具!

道具说明 (Props Explained)

With our Darth Vader case, we actually need two sets of instructions when it comes to commanding the Stormtroopers and other units on the bottom of our chart.

对于我们的达斯·维达案,在指挥图表底部的冲锋队和其他部队时,我们实际上需要两组指令。

Question 1: What should the Stormtroopers do if they encounter the rebels?

问题1:如果突击队遇到叛军,该怎么办?

Answer: Report back to Darth Vader.

答案:向达斯·维达报告。

Question 2: Where should the Stormtroopers travel?

问题2:突击队应该去哪里?

Answer: if the rebels have not been found, search the galaxy at random. Else, go to the rebel location to attack them.

答: 如果 如果找不到反叛者,请随机搜寻星系。 否则 ,前往叛军所在地进行攻击。

Props allow us to continuously monitor the rebelLocation state, and order a troop movement if the state changes. rebelLocation is a string. But what about the orders that must happen when they initially find the rebels?

道具使我们能够连续监视rebelLocation状态,并在状态发生变化时命令部队移动。 rebelLocation是一个字符串。 但是,当他们最初找到叛军时必须执行哪些命令呢?

We can actually pass a function as props as well! That means that we can pass a callback down to each Stormtrooper that will execute if that trooper discovers the target. In the following picture, you can follow the path outlined by “Orders” to trace the props.

实际上,我们也可以将函数作为道具传递! 这意味着我们可以将回调传递给每个突击队员,如果该突击队员发现了目标,它将执行该回调。 在下图中,您可以按照“订单”概述的路径来跟踪道具

In a typical user interface, let’s say that a user clicks a button, and you want to update the state of a parent component. You must also pass a callback from that parent component that will be triggered on the user’s click. That callback can then update the state because it originated with the same parent that set the state.

在典型的用户界面中,假设用户单击一个按钮,而您想更新父组件的状态。 您还必须传递来自该父组件的回调,该回调将在用户单击时触发。 然后,该回调可以更新状态, 因为它源自设置状态的同一父级

This is important, so let’s explore this code line-by-line:

这很重要,因此让我们逐行探讨以下代码:

Line 8: We create the command for the Stormtroopers that they should return with the rebel location immediately when they find it.

第8行:我们为突击队创建了命令,他们在找到突击队时应立即返回叛军所在地。

Line 19: We pass the command to the entire army via the updateLocation props.

第19行 :我们通过updateLocation 道具将命令传递给全军。

Line 32: The Imperial Army passes this command to every Stormtrooper with an identical updateLocation props.

第32行 :帝国军将此命令传递给具有相同的updateLocation 道具的每个突击队员。

Line 42: We create a discoverLocation function so we can pass the value of the input into the updateLocation() callback when it is triggered.

第42行 :我们创建了discoverLocation函数,以便可以在触发输入时将输入的值传递给updateLocation()回调。

Line 53: When a Stormtrooper finds the location, it triggers the discoverLocation() function so we can return the location via updateLocation(). This updates the state in the vadersArmy parent component.

第53行 :当冲锋队找到位置时,它会触发discoverLocation()函数,因此我们可以通过updateLocation()返回该位置。 这将更新vadersArmy父组件中的状态

Other Notes: We passed the rebelLocation all the way down to each Stormtrooper as well. In this tutorial, we will not do anything with that information, but in the future, you can imagine that might be used to shift the location of all troopers towards the rebel base.

其他说明:我们还将rebelLocation一直传递到每​​个突击队。 在本教程中,我们将不会对这些信息做任何事情,但是在将来,您可以想象这可能会被用来将所有士兵的位置移向叛军基地。

最后总结 (A Final Recap)

  1. Darth Vader gives every member of the Galactic Empire an order: If you find the rebels, report back to me immediately. In code, this is a function in the parent vadersArmy component that is then passed to every child via props.

    达斯·维达(Darth Vader)向银河帝国的每个成员下达命令:如果您发现叛军,请立即向我报告。 在代码中,这是父级vadersArmy组件中的一个函数,然后通过props传递给每个子级。

  2. The Army, Navy and Military Intel (three divisions of the Empire) pass this instruction to every single troop, again via props.

    陆军,海军和军事Intel(帝国的三个师)再次通过道具将该指令传递给每个部队。

  3. Each member of the Empire has the instructions. When they encounter the rebels, they will use a callback to pass the location all the way back up to Darth Vader, who will update the entire Empire with the news simultaneously and prepare for battle. This simulates a dynamic user input that changes the state of the parent component.

    帝国的每个成员都有指示。 当他们遇到叛军时,他们将使用回调将位置一路传递回达斯·维德(Darth Vader),后者将同时利用新闻更新整个帝国并为战斗做准备。 这模拟了动态用户输入,该输入更改了父组件的状态

If you enjoyed this post, you may also enjoy my other explanations of challenging CSS and JavaScript topics, such as positioning, Model-View-Controller, and callbacks.

如果您喜欢这篇文章,那么您可能还会喜欢我对具有挑战性CSS和JavaScript主题的其他解释 ,例如定位,Model-View-Controller和回调。

And if you think this might help other people in the same position as you, give it a “heart”!

而且,如果您认为这可以帮助与您处于同一位置的其他人,请给它一个“心脏”!

翻译自: https://www.freecodecamp.org/news/react-props-state-explained-through-darth-vaders-hunt-for-the-rebels-8ee486576492/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值