2017-05-04 76 views
0

我有以下類,它基於排序下拉呈現用戶。如果我選擇「按字母順序排列」,按照字母順序列出用戶,並在我選擇「組」時按組順序排列。Reactjs - 使用componentWillReceiveProps函數中的setState從道具設置狀態

render(){ 
    return(
     const {members, sort} = this.state 
     { sort === "alphabetical" && <SortByAlphabet members={members} /> } 
     { sort === "group" && <SortByGroup members={members}/> } 
    ) 
) 

<SortByAlphabet />部件我設置從props.members組件狀態對象在componentWillReceiveProps()功能。

componentWillReceiveProps = props => { 
    this.setState({ members : props.members }); 
} 

當我選擇「組」之類的,<SortByAlphabet />組件卸載和<SortByGroup />在DOM安裝。再次,當我切換回「按字母排序」排序時,在<SortByAlphabet />組件之前設置的狀態變量(成員)變爲NULL,因爲組件已從DOM中刪除。

componentWillReceiveProps功能不會在第二次觸發時重新渲染<SortByAlphabet /> b'coz道具沒有改變。但我想更新狀態變量,就像我在componentWillReceiveProps函數中第一次那樣更新狀態變量。

如何做到這一點?

回答

3

componentWillMount在組件生命週期中僅在組件生命週期中被調用一次,緊接着組件被呈現之前。它通常用來執行渲染初始前所需的任何狀態變化,因爲在這個方法中調用this.setState不會觸發額外的渲染 所以,你可以更新使用staate

componentWillMount() 
{ 

     this.setState({ members : props.members }); 


} 
+2

我不明白你的意思代碼。你是否真的要重新定義'componentWillReceiveProps'?inside?'componentWillMount'?那會做什麼? –

+1

剛剛設置的狀態裏面willmount –

+0

當然,現在有道理:) –

4

正如@Vikram也表示, componentWillReceiveProps不是第一次調用,因此當組件初始安裝時,您的狀態沒有設置,因此您需要使用componentWillMount/componentDidMount函數中的道具(僅在第一次渲染時調用該道具)設置狀態,以及componentWillReceiveProps函數

componentWillReceiveProps = props => { 
    if(props.members !== this.props.members) { 
     this.setState({ members : props.members }); 
    } 
} 

componentWillMount() { 
    this.setState({ members : this.props.members }); 
} 
相關問題