1. 程式人生 > >react中父元件傳入子元件的值,在子元件不隨著父元件的值變化

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;