深入浅出React的一些细节——State
(来源于: 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的更多相关文章
- 深入浅出 React Native:使用 JavaScript 构建原生应用
深入浅出 React Native:使用 JavaScript 构建原生应用 链接:https://zhuanlan.zhihu.com/p/19996445 原文:Introducing React ...
- 深入浅出React Native 2: 我的第一个应用
这是深入浅出React Native教程的第二篇文章. 1. 环境配置 React Native环境配好之后,就可以开始创建我们的第一个App啦. 打开控制台,输入 react-native init ...
- 深入浅出React Native 3: 从零开始写一个Hello World
这是深入浅出React Native的第三篇文章. 1. 环境配置 2. 我的第一个应用 将index.ios.js中的代码全部删掉,为什么要删掉呢?因为我们准备从零开始写一个应用~学习技术最好的方式 ...
- React使用DVA本地state传值取值
React使用DVA本地state传值取值 最近在用Ant Pro 做一个后台系统,在使用中发现Antd Pro使用DVA来实现redux+sagas+router一系列的功能,比传统方式要方便快捷的 ...
- [转] 深入理解React 组件状态(State)
React 的核心思想是组件化的思想,应用由组件搭建而成,而组件中最重要的概念是State(状态),State是一个组件的UI数据模型,是组件渲染时的数据依据. 一. 如何定义State 定义一个合适 ...
- React中Props 和 State用法
React中Props 和 State用法 1.本质 一句话概括,props 是组件对外的接口,state 是组件对内的接口.组件内可以引用其他组件,组件之间的引用形成了一个树状结构(组件树),如果下 ...
- 深入理解React 组件状态(State)
React 的核心思想是组件化的思想,应用由组件搭建而成,而组件中最重要的概念是State(状态),State是一个组件的UI数据模型,是组件渲染时的数据依据. 一. 如何定义State 定义一个合适 ...
- react中这些细节你注意过没有?
react中的一些细节知识点: 1.组件中get的使用(作为类的getter) ES6知识:class类也有自己的getter和setter,写法如下: Class Component { const ...
- React学习笔记-03 state
每一个组件都有状态,比如一个开关,开 和 关,都是一种state.那么react是怎么管理它的state的? React 把用户界面当做状态机,可以轻松的让用户界面和数据保持一致.用户只需要更新组件的 ...
随机推荐
- 如何在虚拟机安装的Win10系统里快速打开【此电脑】图标?(图文详解)
不多说,直接上干货! 为什么要写写这篇博客? 技多不压身,很多小技巧很重要,方便自己. 比如,对于这样的工具,个人来讲,玩过试用期,意味着你若不找点法子,是不行的.否则你没得玩了. 全网最详细的Tab ...
- 开发工具 -- PyDev的使用
1.创建PyDev工程 2.创建源文件夹src 3.新建.py文件 其他注意事项 1.设置字体大小 2.显示行号Ctrl + F10 3.编码设置为UTF-8 4.最好将工程创建到默认工作空间 5.总 ...
- 神经网络中的池化层(pooling)
在卷积神经网络中,我们经常会碰到池化操作,而池化层往往在卷积层后面,通过池化来降低卷积层输出的特征向量,同时改善结果(不易出现过拟合).为什么可以通过降低维度呢? 因为图像具有一种“静态性”的属性,这 ...
- ASP.NET Core 中的 ORM 之 Entity Framework
目录 EF Core 简介 使用 EF Core(Code First) EF Core 中的一些常用知识点 实体建模 实体关系 种子数据 并发管理 执行 SQL 语句和存储过程 延迟加载和预先加载 ...
- redis实战笔记(8)-第8章 构建简单的社交网站
本章主要内容 用户和状态 主页时间线 关注者列表和正在关注列表 状态消息的发布与删除 流API
- Linux skbuff注释笔记
SKB结构定义 /usr/src/linux/include/linux/skbuff.h sk_buff_head: struct sk_buff_head { //SKB的头结点 /* The ...
- [转]使用EntityFramework6.1的DbCommandInterceptor拦截生成的SQL语句
本文转自:http://www.cnblogs.com/Ax0ne/p/3620958.html 开始 EF6.1也出来不少日子了,6.1相比6.0有个很大的特点就是新增了System.Data.En ...
- xcode 调试器 LLDB
本文完全转载,转载地址:点击这里 你是否曾经苦恼于理解你的代码,而去尝试打印一个变量的值? NSLog(@"%@", whatIsInsideThisThing); 或者跳过一个函 ...
- iOS系统库头文件中NS_AVAILABLE相关
转载: NS_AVAILABLE_IOS(5_0) 这个方法可以在iOS5.0及以后的版本中使用,如果在比5.0更老的版本中调用这个方法,就会引起崩溃. NS_DEPRECATED_IOS(2_0, ...
- log4j2使用教程
Log4j2简介 log4j2是log4j 1.x 的升级版,2015年5月,Apache宣布log4j1.x 停止更新.最新版为1.2.17. log4j2参考了logback的一些优秀的设计, ...