我有以下類,它基於排序下拉呈現用戶。如果我選擇「按字母順序排列」,按照字母順序列出用戶,並在我選擇「組」時按組順序排列。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
函數中第一次那樣更新狀態變量。
如何做到這一點?
我不明白你的意思代碼。你是否真的要重新定義'componentWillReceiveProps'?inside?'componentWillMount'?那會做什麼? –
剛剛設置的狀態裏面willmount –
當然,現在有道理:) –