Component state

实例:

  1. import React, { PureComponent } from 'react';
  2.  
  3. export default class extends PureComponent {

  4. constructor(props) {

  5. super(props);

  6. this.state = { time: '' };

  7. }
  8.  
  9. componentDidMount() {

  10. setInterval(() => {

  11. const now = new Date();

  12. let { time } = this.state;

  13. const year = now.getFullYear();

  14. const month = now.getMonth() + 1;

  15. const day = now.getDate();

  16. const hours = now.getHours();

  17. const minutes = now.getMinutes();

  18. const seconde = now.getSeconds();

  19. time = ${0000${year}.slice(-4)}-${00${month}.slice(-2)}-${00${day}.slice(-2)} ${00${hours}.slice(-2)}:${00${minutes}.slice(-2)}:${00${seconde}.slice(-2)}

  20. this.setState({ time });

  21. }, 1000);

  22. }
  23.  
  24. render() {

  25. return (

  26. <div>{this.state.time}</div>

  27. )

  28. }

  29. }

Timer 在线实例

定义

写在constructor函数中,是一个Object对象。一般情况下需要指定默认值,预防抛undefined.

使用

在组件中通过访问组件对象属性的方式。直接获取:this.state.time.
我们通常会先获取state数据,再渲然到页面,例如:

  1. render() {
  2. const {time} = this.state;
  3. return (
  4. <div>{time}</div>
  5. );
  6. }

setState

先看一段代码:

  1. import React, {PureComponent} from 'react';
  2.  
  3. export default class extends PureComponent {

  4. constructor(props) {

  5. super(props);

  6. this.state = {name: 'world'};

  7. }
  8.  
  9. render() {

  10. const {name} = this.state;

  11. return (

  12. <div>

  13. <input defaultValue={name} name="name" />

  14. <div>Holle, {name}!</div>

  15. </div>

  16. );

  17. }

  18. }

  • 数据单和向性

    inputdiv中直接显示name的内容,但是,在input中直接输入内容,div的显示不会改变。

    把这种组件也称为非受控性组件。

  • setState

    通过React提供了setState方法,来实现state的修改。

    我们只要将上述的非受控性组件修改为受控性组件即可,如下:

    1. <input value={name} onChange={e => this.setState({name: e.target.value})} />

    使用setState方法需要注意以下几点:

    • 异步

      1. onChange () {
      2. this.setState({name: 'hasChanged'})
      3. console.log(this.state.name === 'hasChanged'); //false
      4. }
    • 合并

      1. this.state = {name: 'xiaoshouyi', address: 'beijing'};
      2.  
      3. this.setState({address: 'xi an'});
      4.  
      5. //not

      6. //this.setState({...this.state, addree: 'xi an'});

      7. //但是这种方式在对象修改的时候非常有用。
      8.  
      9. console.log(this.state) //{name: 'xiaoshouyi', address: 'xi an'}

      类似与Object.assgin()

    • 回调

      1. this.setState({name: 'changed'}, () => {
      2. console.log(this.state.name); // changed
      3. });

非控组件 在线实例

受控组件 在线实例

推荐阅读《React 手稿》

原文地址:https://segmentfault.com/a/1190000016946490

React 手稿 - Component state的更多相关文章

  1. React手稿之State Hooks of Hooks

    React Hooks React在16.7.0-alpha.0版本中提到了Hooks的概念,目前还是Proposal阶段. 官方也陈述,接下来的90%的工作会投入到React Hooks中. 从目前 ...

  2. [React] Update Component State in React With Ramda Lenses

    In this lesson, we'll refactor a React component to use Ramda lenses to update our component state. ...

  3. React手稿之 React-Saga

    Redux-Saga redux-saga 是一个用于管理应用程序副作用(例如异步获取数据,访问浏览器缓存等)的javascript库,它的目标是让副作用管理更容易,执行更高效,测试更简单,处理故障更 ...

  4. 说说React组件的State

    说说React组件的State React的核心思想是组件化的思想,应用由组件搭建而成, 而组件中最重要的概念是State(状态). 正确定义State React把组件看成一个状态机.通过与用户的交 ...

  5. React组件的State

    React组件的State 1.正确定义State React把组件看成一个状态机.通过与用户的交互,实现不同状态,然后渲染UI,让用户界面和数据保持一致.组件的任何UI改变,都可以从State的变化 ...

  6. [React] Compound Component (React.Children.map & React.cloneElement)

    Imaging you are building a Tabs component. If looks like: <Tabs> <TabList> <Tab> o ...

  7. [React] Keep Application State in Sync with Browser History

    Using pushState and passing route data via context allows our application to respond to route change ...

  8. React 修改获取state中的值

    14===> 修改state中的值 不能够直接修改 state = { num: 10 } 如 this.state.num+=12; 不能够直接修改 错误 通过 this.setState({ ...

  9. React手稿 - Context

    Context Context提供了除props之外的传参数的方式. Context是全局跨组件传递数据的. API React.createContext ``` const {Provider, ...

随机推荐

  1. VMware 12安装CentOS 6.9时出现:The centos disc was not found in any of your drives.Please insert the centos disc and press OK to retry

    错误: The centos disc was not found in any of your drives.Please insert the centos disc and press OK t ...

  2. innodb_support_xa=1

    mysql> show create table t; CREATE TABLE `t` ( `id` ) NOT NULL AUTO_INCREMENT, `num` ) DEFAULT NU ...

  3. C# SortedDictionary&lt;TKey, TValue&gt; 类

    表示依据键进行排序的键/值对的集合. https://msdn.microsoft.com/zh-cn/library/f7fta44c.aspx

  4. android中图型的阴影效果(shadow-effect-with-custom-shapes)

    思路: 在自己定义shape中添加一层或多层,并错开.就可以显示阴影效果.为添加立体感,button按下的时候,仅仅设置一层.我们能够通过top, bottom, right 和 left 四个參数来 ...

  5. 有一种蓝叫 APEC 蓝

    有如是解释 APEC 者--Air Pollution Eventually Controlled. 有说此次是继零八后的重新万国来朝.丝路大略明白了,西域必通. 站在历史的远处回眸,这是继零八年后重 ...

  6. 初探boost之noncopyable学习笔记

    noncopyable 功能 同意程序轻松实现一个不可复制的类. 需包括头文件 #include<boost/noncopyable.hpp>     或 #include<boos ...

  7. MySQL调优 —— Using temporary

      DBA发来一个线上慢查询问题. SQL例如以下(为突出重点省略部分内容): select distinct article0_.id, 等字段 from article_table article ...

  8. LightOJ--1152--Hiding Gold(二分图奇偶建图)(好题)

    Hiding Gold Time Limit: 2000MS   Memory Limit: 32768KB   64bit IO Format: %lld & %llu Submit Sta ...

  9. Java中的命名规范到底是怎样的

    内容摘要:命名规范二,java中的方法名,对象名和字段名的第一个单词的首写字母应该小写,而后面的每个单词的首字母都应该小写 要想将java基础学的十分的牢固就必须将java中的命名规范掌握好了.俗话说 ...

  10. A - Translation

    Problem description The translation from the Berland language into the Birland language is not an ea ...