react 响应式数据

1.class组件

调用setState修改
1.setState是异步的,多次调用会合并为一次
2.修改同样数值的数据,仍会触发更新(解决方案:使用PureComponent)
复制代码
  class Cc extends React.Component {
    state = {
      a: 1,
      c: [1, 2, 3]
    }
    fix() {
      // 调用setState修改
      // 1.setState是异步的,多次调用会合并为一次
      // 2.修改同样数值的数据,仍会触发更新(解决方案:使用PureComponent)
      this.setState({
        a: this.state.a + 1
      }, () => {
        // 得到异步后的值
        console.log(this.state)
      })
      console.log(this.state)
    }
    fixArr() {
      // 在PureComponent下,数组和对象判断是否改变,由其内存地址判断
      // 一般先拷贝一份,再进行操作
      let _arr = [...this.state.c]
      _arr.push(4)
      this.setState({
        c: _arr
      })
    }
    render() {
      console.log(1)
      return <div>
        <Button type="primary">class组件</Button>
        <div>{this.state.a}</div>
        <div>{this.state.c}</div>
        <Button type="primary" onClick={this.fix.bind(this)}>修改数据</Button>
        <br></br>
        <Button type="primary" onClick={this.fixArr.bind(this)}>修改数组</Button>
      </div>
    }
  }
复制代码

2.函数组件

借用useState hook来解决响应式问题

复制代码
  let [mes, setMsg] = useState(111)
  // mes值本身
  // setMsg修改方法
  function fixMsg() {
    setMsg(mes+1)
  }
  return <div className={styles.container}>
    <div>响应式数据</div>
    <Button type="primary">函数组件</Button>
    <div>{mes}</div>
    <Button type="primary" onClick={fixMsg}>修改数据</Button>
    <Cc></Cc>
  </div>
复制代码

 

posted on   sss大辉  阅读(76)  评论(0编辑  收藏  举报

编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
历史上的今天:
2020-03-26 npm的一些细节
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示