2017-07-11 23 views
1

有一種簡單的方案,我更新了父項中的一個值,該值傳遞給子組件,並且期望cWRP方法觸發,但不是。這裏代碼如下;componentWillReceiveProps甚至沒有發射道具值更新

父組件:

class App extends Component { 
    changeProps(){//interpreter jumps here fine.. 
    debugger 
    this.appState.index=15 //update props value 
    } 
    render() { 
    return (
     <div className="App"> 
     <EasyABC parentUpdateProps={this.changeProps} appState={this.props.appState} /> 
     </div> 
    ) 
    } 
} 

子組件:

@observer 
export default class EasyABC extends Component{ 
    constructor(props){ 
     super(props) 
    } 
    componentWillReceiveProps(nextProps){//why its not jump here after update props in parent? 
     debugger 
    } 
    playSound(){// when this method called, cWRP above should be invoked rigth? 
     this.props.parentUpdateProps() 
    } 

render(){ 
     return(
      <div> 
       <a onClick={()=> this.playSound()}>Play Sound Again</a> 

編輯:我使用mobx作爲國家處理,但不要理會它

回答

1

你需要使用的setState更新組件的狀態,並使用相同的將它傳遞給子組件

class App extends Component { 
 
    constructor() { 
 
    this.state = { 
 
     index: 0, 
 
    }; 
 
    this.changeProps = this.changeProps.bind(this); 
 
    } 
 

 
    changeProps(){ 
 
    this.setState({ 
 
     index: 15, 
 
    }); 
 
    // this will update state (not props) 
 
    } 
 
    render() { 
 
    return (
 
     <div className="App"> 
 
     <EasyABC 
 
      parentUpdateProps={this.changeProps} 
 
      appState={...this.state} 
 
     /> 
 
     </div> 
 
    ); 
 
    } 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

1

要更新錯誤地爲state。您必須使用setState

changeProps() { 
    this.setState({ 
     index: 15 
    }); 
} 
+0

沒有人,我使用mobx不需要本機功能 – TyForHelpDude

0

你必須取消引用的可觀測值渲染函數,或者它不會觸發意願接收道具,因爲該組件實際上並未使用它來渲染。

你可能只是做這樣的事情:

render() { 
    if (this.props.appState.index) { 
    return <div>Play Sound Again</div>; 
    } 

    return <div>Play Sound</div>; 
} 

這真的不要緊,你如何使用它,但你的渲染方法的調用堆棧中訪問它。

相關問題