React 子组件监控父组件

static getDerivedStateFromProps (nextProps, prevState) {
  return {
    pageNo: 1,
    pageSize: 8
  };
}

父组件传值到子组件props中后,props发生变化会自动调用此方法。

其中,pageNo和 pageSize为子组件state中的属性,但并不需要调用setstate。

getDerivedStateFromProps是一个静态函数,也就是这个函数不能通过this访问到class的属性,也并不推荐直接访问属性。而是应该通过参数提供的nextProps以及prevState来进行判断,根据新传入的props来映射到state。

需要注意的是,如果props传入的内容不需要影响到你的state,那么就需要返回一个null,这个返回值是必须的,所以尽量将其写到函数的末尾。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React 中,可以通过 props 将数据从组件传递给组件。如果组件的数据发生变化,可以通过 setState 方法更新组件的状态,并将新的状态传递给组件组件可以通过 componentWillReceiveProps 方法监听组件传递过来的新的 props 值,并根据新的值进行相应的变化。 以下是一个示例代码: ```javascript // 组件 class ParentComponent extends React.Component { constructor(props) { super(props); this.state = { value: '' }; this.handleChange = this.handleChange.bind(this); } handleChange(e) { this.setState({ value: e.target.value }); } render() { return ( <div> <input value={this.state.value} onChange={this.handleChange} /> <ChildComponent inputValue={this.state.value} /> </div> ); } } // 组件 class ChildComponent extends React.Component { constructor(props) { super(props); this.state = { outputValue: '' }; } componentWillReceiveProps(nextProps) { if (nextProps.inputValue !== this.props.inputValue) { this.setState({ outputValue: nextProps.inputValue }); } } render() { return <div>{this.state.outputValue}</div>; } } ``` 在这个示例中,组件中的 input 组件的值发生变化时,会触发 handleChange 方法,更新组件的 value 状态。同时,也会将新的 value 值传递给组件 ChildComponent。当组件接收到新的 inputValue 值时,会触发 componentWillReceiveProps 方法,更新组件的 outputValue 状态。因此,当组件的 value 值发生变化时,组件的内容也会随之变化。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值