React in state and setState

If the data needs to be modified, and at the same page in response to change, we need to put state , and use setState to modify the data, we are here to watch a case study.
1. In the components folder, the new Clock.js , specific code as follows:

// 此时我们导入 Component,下面使用时就可以直接使用,
// 如果不导入 Component,则需要使用 React.Component
import React, { Component } from 'react';

class Clock extends Component {
    // 状态 state 是固定的名字
    state = {
        date: new Date()
    }
    // 找到一个合适的 钩子,写一个定时器,让 date 变量每秒更新
    componentDidMount(){
        const timer = setInterval(() => {
            // setState 也是固定的 api,其中参数可以是 obj 或者 fn
            // this.setState(obj,callback)
            // this.setState(fn,callback)
            this.setState({
                date: new Date()
            })
        },1000)
    }
    componentWillUnmount(){
        // 防止内存泄漏,在组件卸载的钩子里面清除定时器
        clearInterval(this.timer);
    }
    render() {
        return (
            <div>
                {this.state.date.toLocaleTimeString()}
            </div>
        );
    }
}

export default Clock;

2. Then src -> index.js import component, reuse assembly, the execution code in a browser to view the results.

note

  • Please do not modify the status value, as described above if the direct modification date variables, as follows, is not in force,
this.state.date = '直接修改';
  • Batch execution

1. In the components folder, the new StateTest.js , specific code as follows:

import React, { Component } from 'react';

class StateTest extends Component {
    state = {
        counter: 1
    }

    componentDidMount(){
        //  批量执行
        this.setState({ counter: this.state.counter + 1 });
        this.setState({ counter: this.state.counter + 1 });
        this.setState({ counter: this.state.counter + 1 });      
    }
    render() {
        return (
            <div>
                { this.state.counter}
            </div>
        );
    }
}

export default StateTest;

2. Then src -> index.js import StateTest components, and execution will find that even if we are still repeating the output 2 , because setState a batch execution, the above operation will enter a queue, merge operation, before performing the update, found counter performed three times is a redundant operation, so only once, in order to improve update efficiency.

If you just want to continue to perform three times on the results of the last execution (the new value of the variable depends on the old value), please use the function of the method to achieve the specific wording as follows:

componentDidMount(){
    this.setState( prevStatte => ({
        counter: prevStatte.counter + 1
    }))
    this.setState( prevStatte => ({
        counter: prevStatte.counter + 1
    }))
    this.setState( prevStatte => {
        return {
            counter: prevStatte.counter + 1
        }
    })
}

At this time, the output of 4 .

Guess you like

Origin www.cnblogs.com/-muzi/p/11964777.html