美文网首页
【一】React变量渲染和修改数据方式

【一】React变量渲染和修改数据方式

作者: 编程小橙子 | 来源:发表于2020-02-08 20:42 被阅读0次
image.png

两种方式渲染并进行修改数据

import React, { Component } from 'react';
export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
  // 挂载
  componentDidMount() {
    // 方式一:
    /**
     * 1.使用this.setState进行更新数据进行给count赋值
     * 2.在回调中可以得到赋值后最新的值,因为setState是异步的
     */
    this.setState(
      {
        count: this.state.count + 1
      },
      () => {
        console.log(this.state.count, 'start'); //1
      }
    );
    console.log(this.state.count, 'end'); //0
    // 方式二:
    // this.setState(
    //   (prevState, prevProps) => ({
    //     count: prevState.count + 1
    //   }),
    //   () => {
    //     console.log(this.state.count, 'start');  //1
    //   }
    // );
    // console.log(this.state.count, 'end');  //0
  }
  render() {
    return (
      <div>
        <h1>{this.state.count}</h1>
      </div>
    );
  }
}

本次就分享到这里,喜欢的请关注支持下,期待后期更多内容

相关文章

网友评论

      本文标题:【一】React变量渲染和修改数据方式

      本文链接:https://www.haomeiwen.com/subject/ykhwxhtx.html