(来源于: 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. 剑指offer五十六之删除链表中重复的结点

    一.题目 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针. 例如,链表1->2->3->3->4->4->5 处理后 ...

  2. Android的相关事件

    Android的相关事件 1.Toast信息提醒 import android.support.v7.app.AppCompatActivity; import android.os.Bundle; ...

  3. Jar包的格式

    jar包目录格式: |-- com | |-- test.class |-- META-INF | |-- MAINFEST.MF 一个正常的jar包下必有META-INF/MANIFEST.MF清单 ...

  4. OpenGL10-骨骼动画原理篇(3)-Shader版本代码已经上传

    视频教程请关注 http://edu.csdn.net/lecturer/lecturer_detail?lecturer_id=440 接上一个例程OpenGL10-骨骼动画原理篇(2),对骨骼动画 ...

  5. 一款高效视频播放控件的设计思路(c# WPF版)

    因工作的需要,开发了一款视频播放程序.期间也经历许多曲折,查阅了大量资料,经过了反复测试,终于圆满完成了任务. 我把开发过程中的一些思路.想法写下来,以期对后来者有所帮助. 视频播放的本质 就是连续的 ...

  6. ELK日志系统之使用Rsyslog快速方便的收集Nginx日志

    常规的日志收集方案中Client端都需要额外安装一个Agent来收集日志,例如logstash.filebeat等,额外的程序也就意味着环境的复杂,资源的占用,有没有一种方式是不需要额外安装程序就能实 ...

  7. freeSWITCH之多平台测试通信

    开始测试使用 强烈建议在统一的局域网下进行配置,通信 本机IP:192.168.1.155 架构 freeSWITCH搭建在以Windows平台作为通信服务器.fs_cli为服务器上测试客户端. X- ...

  8. springboot-26-springboot 集成rabbitmq

    rabbitmq是基于AMQP规范的一个消息代理, 它可以兼容jms, 支持其他语言, 并且可以跨平台 1, 安装 1) 普通安装 度娘: 2) docker 安装 sudo docker run - ...

  9. 不开vip会员照样看vip电影(亲测有效)

    此为临时链接,仅用于文章预览,将在短期内失效关闭 不开vip会员照样看vip电影(亲测有效) 2018-03-08 mr_lee Python达人课堂 刚刚测试,真实有效,颇不接待要分享了... 土豪 ...

  10. 面试:C/C++常见库函数实现

    1. void *mymemcpy(void *dest, const void* src, size_t n): 内存拷贝函数,memcpy函数的功能是从源src所指的内存地址的起始位置开始拷贝n个 ...