(来源于: https://facebook.github.io/react/docs/state-and-lifecycle.html 翻译by:@TimRChen)

Using State Correctly

There are three things you should know about setState().

1.Do Not Modify State Directly

For example, this will not re-render a component:

// Wrong
this.state.comment = 'Hello';

Instead, use setState():

// Correct
this.setState({comment: 'Hello'});

The only place where you can assign this.state is the constructor.

2.State Updates May Be Asynchronous

React may batch multiple setState() calls into a single update for performance.

Because this.props and this.state may be updated asynchronously(异步的), you should not rely on their values for calculating the next state(你不应该依赖它们计算的值传递给下一个状态).

For example, this code may fail to update the counter:

// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});

To fix it, use a second form of setState() that accepts a function rather than an object(接受一个回调函数而不是一个对象). That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:

// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));

We used an arrow function(ES6箭头函数) above, but it also works with regular functions:

// Correct
this.setState(function(prevState, props) {
return {
counter: prevState.counter + props.increment
};
});

The Data Flows Down

Neither parent nor child components can know if a certain component is stateful or stateless, and they shouldn't care whether it is defined as a function or a class.

This is why state is often called local or encapsulated. It is not accessible to any component other than the one that owns and sets it. (除了组件本身,其他组件无法调用该组件的state)

A component may choose to pass its state down as props to its child components: (一个组件可以选择将它的state作为props传递给它的子组件)

<h2>It is {this.state.date.toLocaleTimeString()}.</h2>

This also works for user-defined(自定义) components:

<FormattedDate date={this.state.date} />

The FormattedDate component would receive the date in its props and wouldn't know whether it came from the Clock's state, from the Clock's props, or was typed by hand(FormattedDate组件会在它的props中获得date,并且不会知道date来自Clock组件的state,还是来自Clock组件的props,或是手动输入的):

function FormattedDate(props) {
return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
}

Try it on CodePen.(<——代码链接)

This is commonly called a "top-down" or "unidirectional" data flow(单向数据流). Any state is always owned by some specific component, and any data or UI derived from that state can only affect components "below" them in the tree. (任何state都属于具体的组件,任何来自与该state的数据或者UI都只能影响低于该state所在组件下的子组件——>也就是说当前state所在组件默认为父组件)

If you imagine a component tree as a waterfall of props, each component's state is like an additional water source that joins it at an arbitrary point but also flows down. (假如将组件树作为props瀑布,每个组件的state就好比加入到整个props瀑布中作为一个任意点的水源,而不是水流)

To show that all components are truly isolated(相互独立), we can create an App component that renders three <Clock>s:

function App() {
return (
<div>
<Clock />
<Clock />
<Clock />
</div>
);
} ReactDOM.render(
<App />,
document.getElementById('root')
);

Try it on CodePen. (<——代码链接)

Each Clock sets up its own timer and updates independently.(每一个Clock组件建立它们自己的定时器并且互不干扰地进行更新)

In React apps, whether a component is stateful or stateless is considered an implementation detail of the component that may change over time. You can use stateless components inside stateful components, and vice versa.(你可以使用无状态的组件在充满了状态的组件中,反之亦然)

总结:今天深入浅出的总结了下关于React中的state使用中的一些细节,以及state与props之间的一些牵连。

ps: 转载请注明出处。@TimRChen

深入浅出React的一些细节——State的更多相关文章

  1. 深入浅出 React Native:使用 JavaScript 构建原生应用

    深入浅出 React Native:使用 JavaScript 构建原生应用 链接:https://zhuanlan.zhihu.com/p/19996445 原文:Introducing React ...

  2. 深入浅出React Native 2: 我的第一个应用

    这是深入浅出React Native教程的第二篇文章. 1. 环境配置 React Native环境配好之后,就可以开始创建我们的第一个App啦. 打开控制台,输入 react-native init ...

  3. 深入浅出React Native 3: 从零开始写一个Hello World

    这是深入浅出React Native的第三篇文章. 1. 环境配置 2. 我的第一个应用 将index.ios.js中的代码全部删掉,为什么要删掉呢?因为我们准备从零开始写一个应用~学习技术最好的方式 ...

  4. React使用DVA本地state传值取值

    React使用DVA本地state传值取值 最近在用Ant Pro 做一个后台系统,在使用中发现Antd Pro使用DVA来实现redux+sagas+router一系列的功能,比传统方式要方便快捷的 ...

  5. [转] 深入理解React 组件状态(State)

    React 的核心思想是组件化的思想,应用由组件搭建而成,而组件中最重要的概念是State(状态),State是一个组件的UI数据模型,是组件渲染时的数据依据. 一. 如何定义State 定义一个合适 ...

  6. React中Props 和 State用法

    React中Props 和 State用法 1.本质 一句话概括,props 是组件对外的接口,state 是组件对内的接口.组件内可以引用其他组件,组件之间的引用形成了一个树状结构(组件树),如果下 ...

  7. 深入理解React 组件状态(State)

    React 的核心思想是组件化的思想,应用由组件搭建而成,而组件中最重要的概念是State(状态),State是一个组件的UI数据模型,是组件渲染时的数据依据. 一. 如何定义State 定义一个合适 ...

  8. react中这些细节你注意过没有?

    react中的一些细节知识点: 1.组件中get的使用(作为类的getter) ES6知识:class类也有自己的getter和setter,写法如下: Class Component { const ...

  9. React学习笔记-03 state

    每一个组件都有状态,比如一个开关,开 和 关,都是一种state.那么react是怎么管理它的state的? React 把用户界面当做状态机,可以轻松的让用户界面和数据保持一致.用户只需要更新组件的 ...

随机推荐

  1. 简述ARP请求过程(同一子网和不同子网)

    1. 同一子网 主机A在准备构造链路层以太网帧头时,首先根据目的IP去查找ARP表,如果找到对应项,则直接得到目的MAC地址,如果没有查到才执行上面所说的ARP广播请求.这样做是为了最大限度地减少广播 ...

  2. (转)CentOS7使用ACL精确控制文件和目录的访问权限

    原文:https://www.linuxidc.com/Linux/2018-01/150111.htm https://blog.csdn.net/maxiaoqiang1/article/deta ...

  3. 根据屏幕尺寸计算rem

    !(function (doc, win) { var docEle = doc.documentElement, evt = "onorientationchange" in w ...

  4. 玩转mongodb(二):mongodb基础知识

    常用基本数据类型: null null用于表示空值或者不存在的字段: {"data":null} 布尔型 布尔类型只有两个值,true和false: {"data&quo ...

  5. SpringBoot入门 (三) 日志配置

    上一篇博文记录了再springboot项目中读取属性文件中配置的属性,本文学习在springboot项目中记录日志. 日志记录在项目中是很常见的一个功能了,对排查问题有很大帮助,也可以做分类分析及统计 ...

  6. 【起】ACM类下为过往所做过的部分算法题目

    [起]ACM类下为过往所做过的部分算法题目 几百道题,日后细细品味.

  7. 高云的jQuery源码分析笔记

    (function( window, undefined ) { // 构造jQuery对象 var jQuery = function( selector, context ) { return n ...

  8. python单链表

    #!/usr/bin/env python3 # -*- coding:utf-8 -*- class LNode: """ 结点类 """ ...

  9. [转]C#综合揭秘——Entity Framework 并发处理详解

    本文转自:http://www.cnblogs.com/leslies2/archive/2012/07/30/2608784.html 引言 在软件开发过程中,并发控制是确保及时纠正由并发操作导致的 ...

  10. [LeetCode] Next Permutation(一种巧妙的解题方法)

    Next Permutation Implement next permutation, which rearranges numbers into the lexicographically nex ...