react中如何使用状态提升?

在 React 中,将多个组件中需要共享的 state 向上移动到它们的最近共同父组件中,便可实现共享 state。这就是所谓的“状态提升”。

代码解读:

实现方式是 利用最近的共同的父级组件中,用props的方式传过去到两个子组件,props中传的是一个setState的方法,通过子组件触发props传过去的方法,进而调用父级组件的setState的方法,改变了父级组件的state,调用父级组件的add方法,进而同时改变了两个子级组件的数据

代码片段:

import React, { Component } from 'react';

class Child1 extends Component {
  // state = { count: 1 }
  render () {
    return (
      <>
        <h1>child1组件</h1>
        {/* { this.state.count } */}
        { this.props.count }
        {/* <button onClick={ () => { this.setState({count: this.state.count + 1} ) }}>加1</button> */}
        <button onClick={ this.props.onClick }>加1</button> 
      </>
    )
  }
}
class Child2 extends Component {
  // state = { count: 1 }
  render () {
    return (
      <>
        <h1>child2组件</h1>
       {/* { this.state.count } */}
       { this.props.count }
        {/* <button onClick={ () => { this.setState({count: this.state.count + 1} ) }}>加1</button> */}
        <button onClick={ this.props.onClick }>加1</button> 
      </>
    )
  }
}
class App extends Component {
  state = { count: 1 }
  add = () => {
    this.setState({count: this.state.count + 1})
  }
  render() {
    return (
      <div>
        <Child1 count = { this.state.count } onClick = { this.add }></Child1>
        <hr></hr>
        <Child2 count = { this.state.count } onClick = { this.add }></Child2>
      </div>
    );
  }
}

export default App;

这是 两个有关连的同级组件的传值,因为react的单项数据流,所以不在两个组件中进行传值,而是提升到 最近的共同的父级组件中,改变父级的state,进而影响了两个子级组件的render

注意如果两个组件是同级组件(这两个组件的父组件是同一个)才考虑状态提升,共享数据

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值