(来源于: 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. Vuejs 整合 MUi

    整合方法和使用axios的方法类似.具体步骤如下: 引入mui的css和js import mui from './lib/mui/js/mui.js' import './lib/mui/css/m ...

  2. 关于Item

    0.Item The base class of all items, which implements default behavior. 项(Item)代表一个字节码中可以寻址的实体,有许多种类的 ...

  3. SpringMVC和dubbo简单的整合(附Demo)

    顺便记录下apache产品提供下载的网址:http://mirrors.shuosc.org/apache/ 第一步: 下载zookeeper,网址:http://mirrors.shuosc.org ...

  4. Redis笔记(五):Redis发布订阅

    Redis 发布订阅 Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息. Redis 客户端可以订阅任意数量的频道. 下图展示了频道 cha ...

  5. Cloudera Impala源码分析: SimpleScheduler调度策略详解包括作用、接口及实现等

    问题导读:1.Scheduler任务中Distributed Plan.Scan Range是什么?2.Scheduler基本接口有哪些?3.QuerySchedule这个类如何理解?4.Simple ...

  6. CentOS rar

    基本unrar用法: unrar x -o- -y heidian.rar /var/www/ (把heidian.rar 文件,解压到/var/www/ 目录.要注意/ 结束)

  7. redis实战笔记(9)-第9章 降低内存占用

    本章主要内容   1.短结构( short structure) 2.分片结构( shared structure) 3.打包存储二进制位和字节   本章将介绍3种非常有价值的降低Redis内存占用的 ...

  8. ANTLR4权威指南 - 第6章 尝试一些实际中的语法

    第6章 尝试一些实际中的语法 在前一章,我们学习了通用词法结构和语法结构,并学习了如何用ANTLR的语法来表述这些结构.现在,是时候把我们学到的这些用来构建一些现实世界中的语法了.我们的主要目标是,怎 ...

  9. JAVA-6NIO之FileChannel

    Java NIO中的FileChannel是一个连接到文件的通道.可以通过文件通道读写文件. FileChannel无法设置为非阻塞模式,它总是运行在阻塞模式下. 打开FileChannel 在使用F ...

  10. Asp.net MVC中关于@Html标签Label、Editor使用

    @Html帮助器简单说明,记录些基本的跟HTML中对应的@html帮助器,@Html基本包含了html中的表单控件和常用Html在@Html中,带有For的主要是针对强类型的Html类型.用于说明@H ...