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;
发布了115 篇原创文章 · 获赞 38 · 访问量 43万+

猜你喜欢

转载自blog.csdn.net/wangweiscsdn/article/details/82109797