一个React初学者的常见错误

React中子组件会跟随父组件的render而render,但需要注意的是子组件的render并非重建,此时是不会重新走构造函数的,很多人容易忽视这点,而出现一下错误

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: this.props.value };
  }
  
  render() {
    return <div>The value is: {this.state.value}</div>
  }
}


class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = { value : 1}
    }
    render() {
        <Child value={this.state.value}>
        <button  onClick={() => setState({ value : 2})}>
            Click me
        </button>
    }

}

点击Parent的Button后,Child仍然是1而不会变为2,因为Child的构造函数没有重新执行,props的值也不会更新。正确的做法是不要将props赋值给state,而应在render方法中使用this.props.value。

但是有一种情况,props的value在render之前会进行复杂的计算,此时为了避免无意义的性能开销,还是希望用state进行保存,那应该怎么做呢?可以使用如下方式:

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: this.props.value };
  }
  handle(value) {
        /*do sth expensive*/
        return value
  }
  componentWillReceiveProps(nextProps) {
    if(nextProps.value !== this.props.value) {
      this.setState({value: handle(nextProps.value)}));
    }
  }
  render() {
    return <div>The value is: {this.state.value}</div>
  }
}

或者使用更优雅的souldComponentUpdate:

class Child extends React.Component {
    
    shouldComponentUpdate(nextProps, nextState) {
        return nextProps.value !== this.pros.value
    }

    handle(value) {
        /*do sth expensive*/
        return value
    }
        
    render() {
        return <div>The value is: { handle(this.state.value) }</div>
      }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fundroid

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值