react单向数据流_React中的单向数据流

react单向数据流

Unidirectional Data Flow is not a concept unique to React, but as a JavaScript developer this might be the first time you hear it.

单向数据流并不是React独有的概念,但是作为JavaScript开发人员,这可能是您第一次听到它。

In general this concept means that data has one, and only one, way to be transferred to other parts of the application.

通常,此概念意味着数据只有一种方式可以传输到应用程序的其他部分。

In React this means that:

在React中,这意味着:

  • state is passed to the view and to child components

    状态传递给视图和子组件
  • actions are triggered by the view

    操作由视图触发
  • actions can update the state

    动作可以更新状态
  • the state change is passed to the view and to child components

    状态更改将传递到视图和子组件

react单向数据流_React中的单向数据流

The view is a result of the application state. State can only change when actions happen. When actions happen, the state is updated.

该视图是应用程序状态的结果。 国家只有在采取行动时才能改变。 当动作发生时,状态被更新。

Thanks to one-way bindings, data cannot flow in the opposite way (as would happen with two-way bindings, for example), and this has some key advantages:

得益于单向绑定,数据不能以相反的方式流动(例如,双向绑定会发生这种情况),这具有一些关键优势:

  • it’s less error prone, as you have more control over your data

    它更不容易出错,因为您可以更好地控制数据
  • it’s easier to debug, as you know what is coming from where

    它更容易调试,因为你知道是从哪儿

  • it’s more efficient, as the library already knows what the boundaries are of each part of the system

    因为该库已经知道系统各部分的边界,所以效率更高

A state is always owned by one Component. Any data that’s affected by this state can only affect Components below it: its children.

状态始终由一个组件拥有。 受此状态影响的任何数据只能影响其下的组件:其子组件。

Changing state on a Component will never affect its parent, or its siblings, or any other Component in the application: just its children.

更改组件上的状态永远不会影响其父代,其兄弟姐妹或应用程序中的任何其他组件:仅影响其子代。

This is the reason that the state is often moved up in the Component tree, so that it can be shared between components that need to access it.

这就是状态通常在组件树中上移的原因,以便可以在需要访问它的组件之间共享状态。

翻译自: https://flaviocopes.com/react-unidirectional-data-flow/

react单向数据流