(来源于: 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. Redis客户端使用

    http://wenku.baidu.com/view/6ccd650af12d2af90242e63d.html 一.下载jedis 代码 jedis 代码地址:https://github.com ...

  2. MVC的默认约定

    MVC项目中有很多默认约定,一种是对项目目录分配的约定,比如默认情况下需要将Javascript文件放置在Script文件夹中,但这并不妨碍你将这个文件夹重新命名,也可以将整个文件夹放置到任何想要放置 ...

  3. 【C#小知识】C#中一些易混淆概念总结---------数据类型存储,方法调用,out和ref参数的使用

    这几天一直在复习C#基础知识,过程中也发现了自己以前理解不清楚和混淆的概念.现在给大家分享出来我的笔记: 一,.NET平台的重要组成部分都是有哪些 1)FCL (所谓的.NET框架类库) 这些类是微软 ...

  4. CSS3中的pointer-events

    今天做项目中偶然误把元素加上了pointer-events属性,结果导致后来在js中给该元素加点击事件不能用,检查了半天才发现是这个属性的问题.之前没有好好研究,于是决定仔细研究一下. 一.定义及语法 ...

  5. C/C++ -- Gui编程 -- Qt库的使用 -- 理解主窗体构造函数

    MyWidget做父窗体 MyWidget的构造函数中可以手动添加组件 Ui::MyWidget存放子部件 Ui::MyWidget执行setupUi()函数为子部件开辟空间,指定父窗体 MyWidg ...

  6. ubuntu 16.04 安装PhpMyAdmin

    首先,安装mysql $ sudo apt-get install mysql-server $ sudo apt-get install mysql-client 安装时输出root用户的密码 然后 ...

  7. sublime text3怎么让左侧显示目录树

    在前端开发中(包括Node.js开发),经常会使用sublime text,但之前一直不知道别人是怎么让左侧显示目录树,故特意在此记录一下. View ->Side Bar ->Show ...

  8. vue里面computed的运用理解

    computed 计算属性,是用来声明式的描述一个值依赖了其它的值,当你在模板里把数据绑定到一个计算属性上时,Vue 会在其依赖的任何值导致该计算属性改变时更新 DOM.这个功能非常强大,它可以让你的 ...

  9. 任务三十七:UI组件之浮出层

    任务三十七:UI组件之浮出层 面向人群: 有一定JavaScript基础 难度: 低 重要说明 百度前端技术学院的课程任务是由百度前端工程师专为对前端不同掌握程度的同学设计.我们尽力保证课程内容的质量 ...

  10. [转]VS2012正则查找

    本文转自:http://blog.csdn.net/u013688451/article/details/52840325 工作中有时需要用到 正则查找,例如 想找 所有用到 某个数据库表的地方 st ...