鍍金池/ 問答/C++  網(wǎng)絡(luò)安全  HTML/ react中父層變量傳入子層,改變父層變量,子層變量沒變

react中父層變量傳入子層,改變父層變量,子層變量沒變

// Father.js
class Father extends Component {
  constructor(props){
    super(props);
    this.state = {
      reset: 'unreset',
      father: {
        name:'father'
      }
    };
    this.resetData = this.resetData.bind(this);
  }
  resetData () {
    this.setState({
      father: {
        name:'father 2'
      }
    });
  }
  render() {
    return (
      <div className="App">
        <Child father={this.state.father} resetData={this.resetData}/>
      </div>
    );
  }
}
export default Father;
// Child.js
class Child extends Component {
  constructor(props){
    super(props);
    const {father} = this.props;
    this.state = {
      isChange: 'unChange',
      father: father,
    };
    this.change = this.change.bind(this);
  }
  change () {
    this.setState({
      isChange: 'change',
    });
    setTimeout(this.props.resetData,2000);
  }
  render() {
    return (
      <div className="App" onClick={this.change}>
        {this.state.isChange}
        <br/>
        {this.props.father.name}
        <br/>
        {this.state.father.name}
      </div>
    );
  }
}
export default Child;

為什么點擊之后只有一個改變?
點擊前
圖片描述
點擊后
圖片描述

回答
編輯回答
不討喜

1.兩個father變量都是引用類型,但是父組件的resetData直接改變了father的地址,子組件引用的仍然是舊的father

2.你只在構(gòu)造函數(shù)內(nèi)把props.father的值賦給了state.father,后面隨著props.father的改變,state.father并不會主動響應(yīng),原因見上一點

3.解決方法有兩種:
1)全都用props.father
2)添加componentWillReceiveProps函數(shù):

componentWillReceiveProps = (nextProps) => {
  this.setState({
    father: nextProps.father
  })
}
2018年2月11日 08:50
編輯回答
獨白

1.你在子組件里把父組件傳過來的props用state緩存起來了,由于父組件屬性更新的時候子組件不會重新渲染,不會再走構(gòu)造函數(shù),所以子組件的state不會和父組件的props保持同步,這個時候你需要在componentWillReceiveProps(nextProps) 里去處理
2.也可以不緩存到state里,直接在render函數(shù)里用父組件傳過來的props

2017年10月15日 21:04
編輯回答
毀了心

var a,b;
a='father';
b=a;
console.log(a,b);
a='father 2';
console.log(a,b);
你考慮考慮上面這段代碼結(jié)果是什么

2018年9月13日 07:18
編輯回答
遺莣

在state發(fā)生變化時,重新渲染組件,是不會再走super()方法的,會重新調(diào)用render()方法,因此,子組件this.state.father.name,你在super()聲明而已,并沒有發(fā)生變化。

2017年7月15日 07:09
編輯回答
冷眸

我記得在constructor中通過this.props是取不到值的

不好意思~ 我搞錯了了~

2017年2月27日 14:28