一个React初学者的常见错误

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

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: this.props.value };
  }
  
  render() {
    return 
The value is: {this.state.value}
} } class Parent extends React.Component { constructor(props) { super(props); this.state = { value : 1} } render() { } }

点击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 
The value is: {this.state.value}
} }

或者使用更优雅的souldComponentUpdate:

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

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

 

你可能感兴趣的:(React,React)