react中父级props改变,更新子级state的多种方法

本文介绍了三种更新React子组件的方法:使用key强制刷新、通过ref调用子组件方法(不符合React设计规范)、父组件传递数据至子组件进行状态更新。并详细解释了每种方法的应用场景及优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

子组件:

class Children extends Component {
  constructor(props) {
     super(props);
     this.state = {
       a: this.props.a,
       b: this.props.b,
       treeData: '',
       targets: '',
     }
    }
  componentDidMount() {
   const { a, b } = this.state
   const data = {a,b}
   fetch('/Url', {
     data
   }).then(res => {
   if (res.code === 0) {
     this.setState({
     treeData: res.a,
     targets: res.b,
  })
  } else {
   message.error(res.errmsg)
  }
  })
  }
 test(item1, item2) {
   const data = { item1, item2 }
   fetch('/Url', {data}).then(res => {
     if (res.code === 0) {
       this.setState({
         treeData: res.a,
         targets: res.b,
       })
     } else {
       message.error(res.errmsg)
     }
   })
 }
} export
default Children

方法一:巧用key

<Children key={this.state.key} a={this.state.a} b={this.state.b} /> //父组件调用子组件

这种方法是通过key变化子组件会重新实例化 (react的key变化会销毁组件在重新实例化组件)

方法二:利用ref父组件调用子组件函数(不符合react设计规范,但可以算一个逃生出口嘻嘻~)

class father extends Component {
    constructer(props) {
      super(props);
      this.state={
a: '1',
b: '2',
}
this.myRef this.test = this.test.bind(this) } change() {
const { a,b } = this.state console.log(
this.myRef.test(a,b)) // 直接调用实例化后的Children组件对象里函数 } render() { <Children wrappedComponentRef={(inst) => { this.myRef = inst } } ref={(inst) => { this.myRef = inst } } /> <button onClick={this.test}>点击</button> } }

注:wrappedComponentRef是react-router v4中用来解决高阶组件无法正确获取到ref( 非高阶组件要去掉哦)

方法三:父级给子级传数据,子级只负责渲染(最符合react设计观念)推荐!!

父组件:

class father extends Component {
    constructer(props) {
      super(props);
      this.state={
       a:'1',
       b:'2',
       data:'',
      }
    }
  getcomposedata() {
    const { a, b } = this.state
    const data = { a, b }
    fetch('/Url', {data}).then(res => {
      if (res.code === 0) {
        this.setState({
          data:res.data
        })
      } else {
        message.error(res.errmsg)
      }
    })
  }
render() {
 <Children data={this.state.data}} />  
}
}    

子组件:

  componentWillReceiveProps(nextProps) {
    const { data } = this.state
    const newdata = nextProps.data.toString()
    if (data.toString() !== newdata) {
      this.setState({
        data: nextProps.data,
      })
    }
  }
注:react的componentWillReceiveProps周期是存在期用改变的props来判断更新自身state

 

转载于:https://www.cnblogs.com/xiaoxiao666/p/8423319.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值