2017-05-08 145 views
1

我試圖通過另一個組件更改其中一個組件的狀態。請注意,我是新來reactJs

在我父母組件我有一個狀態命名爲:_SPCommandBarDisabled從另一個組件更新一個React的組件狀態

this.state = { 
    _SPCommandBarDisabled: true 
} 

孩子分量(SPSearchBox)事件被觸發時更改狀態_SPCommandBarDisabled(日誌顯示狀態實際發生更改)

public onSearchTextChanged(newText: any) { 
this.setState({ _SPCommandBarDisabled: false }, 
() => { console.log("New _SPCommandBarDisabled: " + this.state._SPCommandBarDisabled) } 
); 

但是,在我的第二個孩子(SPCommandBar組件)中,值未更新。

這是代碼從我的父母組件

export default class StudentDocumentsHelper extends React.Component<IStudentDocumentsHelperProps, any> { 
    constructor() { 
    super(); 

    this.state = { 
     _SPCommandBarDisabled: true 
    } 
    this.onSearchTextChanged = this.onSearchTextChanged.bind(this); 
    } 

    public render(): React.ReactElement<IStudentDocumentsHelperProps> { 
    return (
     <div> 
     <SPCommandBar isDisabled={this.state._SPCommandBarDisabled} /> 
     <SPSearchBox onTextChange={this.onSearchTextChanged} /> 
     <SPListView /> 
     </div> 
    ); 
    } 

    public onSearchTextChanged(newText: any) { 
    this.setState({ _SPCommandBarDisabled: false }, 
    () => { console.log("New _SPCommandBarDisabled: " + this.state._SPCommandBarDisabled) } 
    ); 
    } 
} 

而且從道具

export interface ISPCommandBar { 
    isDisabled: boolean; 
} 

export class SPCommandBar extends React.Component<ISPCommandBar, any> { 
    constructor(props: any) { 
     super(props); 

     this.state = { 
      _SPCommandBarDisabled: this.props.isDisabled 
     }; 
    } 

SPCommandBar繼承更新

在我的SPCommandBar組件我繼承了_SPCommandBarDisabled prop並將其解析爲狀態。

在我SPCommandBar的render()方法,我設置了參照國家啓用值:

disabled: this.state._SPCommandBarDisabled 

和更新家長狀態的時候,孩子的狀態似乎不是沒得到更新。然而,指的是道具,而不是它是工作時的狀態:

disabled: this.props.isDisabled 

我不知道我剛剛解決我自己的問題,或者這是它應該做的方式嗎?原始的海報後

回答

2

編輯找到了解決辦法:

的構造函數只調用一次,當創建組件,當道具,你傳遞給組件的變化,構造函數不會再次調用,但而componentWillReceiveProps,你可以閱讀更多here

原來的答案:

我認爲錯誤是你用這個。道具,而不只是道具

嘗試(這是在構造函數的定義傳遞)來改變這一點:

this.state = { 
    _SPCommandBarDisabled: props.isDisabled 
}; 
+0

不,不幸的是,** _ ** SPCommandBarDisabled在SPCommandBar組件 –

+0

不會改變啊,只是讀取你的更新,的確,你做的不正確,你的組件構造函數只被調用一次,當它被創建時,如果道具改變,那麼狀態將不會被更新,你要找的是直接的使用道具(並且負責處理其餘部分),或者在構造函數和componentWillReceiveProps中綁定它。 – ospfranco

相關問題