Component state

实例:

import React, { PureComponent } from 'react';

export default class extends PureComponent {
  constructor(props) {
    super(props);
    this.state = { time: '' };
  }

  componentDidMount() {
    setInterval(() => {
      const now = new Date();
      let { time } = this.state;
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const day = now.getDate();
      const hours = now.getHours();
      const minutes = now.getMinutes();
      const seconde = now.getSeconds();
      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)}`
      this.setState({ time });
    }, 1000);
  }

  render() {
    return (
      <div>{this.state.time}</div>
    )
  }
}

Timer 在线实例

定义

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

使用

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

    render() {
      const {time} = this.state;
      return (
        <div>{time}</div>
      );
    }

setState

先看一段代码:

import React, {PureComponent} from 'react';

export default class extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {name: 'world'};
  }

  render() {
    const {name} = this.state;
    return (
      <div>
        <input defaultValue={name} name="name" />
        <div>Holle, {name}!</div>
      </div>
    );
  }
}
  • 数据单和向性

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

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

  • setState

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

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

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

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

    • 异步

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

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

      类似与Object.assgin()

    • 回调

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

非控组件 在线实例

受控组件 在线实例

results matching ""

    No results matching ""