react中父組件傳入子組件的值,在子組件不隨着父組件的值變化

這個也是在實際項目中遇到的坑,畢竟我比較年輕~_~

先來個父組件的代碼:

// 父組件
class Car extends Component {
  constructor(props){
    super(props);
    this.state = {
      smallCar: {
        color:'red'
      }
    };
    this.resetCar = this.resetCar.bind(this);
  }
  resetCar () {
    this.setState({
      smallCar: {
        color:'pink'
      }
    });
  }
  render() {
    return (
      <div className="App">
        <SmallCar smallCar={this.state.smallCar} resetCar={this.resetCar}/>
      </div>
    );
  }
}
export default Car;

再來個子組件:

//  子組件
class SmallCar extends Component {
  constructor(props){
    super(props);
    const { smallCar } = this.props;
    this.state = {
      isChange: 'unchange',
      smallCar:smallCar,
    };
    this.change = this.change.bind(this);
  }
  change () {
    this.setState({
      isChange: 'change',
    });
    setTimeout(this.props.resetCar,2000);
  }
  render() {
    return (
      <div className="App" onClick={this.change}>
        {this.state.isChange}
        <br/>
        {this.props.smallCar.name}
        <br/>
        {this.state.smallCar.name}
      </div>
    );
  }
}
export default SmallCar;

兩個smallCar變量都是引用類型,但是父組件的resetCar直接改變了smallCar的地址,子組件引用的仍然是舊的smallCar。

你只在構造函數內把props.smallCar的值賦給了state.smallCar,後面隨着props.smallCar的改變,state.smallCar並不會跟着變化。

1)全都用props.smallCar,這個就不展開了
2) 添加componentWillReceiveProps函數:

//  子組件
class SmallCar extends Component {
  constructor(props){
    super(props);
    const { smallCar } = this.props;
    this.state = {
      isChange: 'unchange',
      smallCar:smallCar,
    };
    this.change = this.change.bind(this);
  }
    // 加上我
    componentWillReceiveProps = (nextProps) => {
      this.setState({
        smallCar: nextProps.smallCar
      })    
    }

  change () {
    this.setState({
      isChange: 'change',
    });
    setTimeout(this.props.resetCar,2000);
  }
  render() {
    return (
      <div className="App" onClick={this.change}>
        {this.state.isChange}
        <br/>
        {this.props.smallCar.name}
        <br/>
        {this.state.smallCar.name}
      </div>
    );
  }
}
export default SmallCar;

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章