我有以下基于渲染下拉列表呈现用户的类。如果我选择“字母”,则将按字母顺序列出用户;当我选择“组”时,将按组顺序列出用户。
render(){ return( const {members, sort} = this.state { sort === "alphabetical" && <SortByAlphabet members={members} /> } { sort === "group" && <SortByGroup members={members}/> } ) )
在<SortByAlphabet />组件中,我正在通过props.members中的componentWillReceiveProps()函数设置组件状态对象。
<SortByAlphabet />
componentWillReceiveProps()
componentWillReceiveProps = props => { this.setState({ members : props.members }); }
当我选择“组”排序时,<SortByAlphabet />组件正在卸载并且<SortByGroup />正在DOM中安装。同样,当我切换回“字母”排序时,在<SortByAlphabet />组件中预先设置的状态变量(成员)将变为NULL,因为该组件已从DOM中删除。
<SortByGroup />
componentWillReceiveProps重新渲染<SortByAlphabet />b’coz时道具未更改时,该功能未触发第二次。但是我想像在componentWillReceiveProps函数中第一次那样更新状态变量。
componentWillReceiveProps
怎么做?
componentWillMount在组件生命周期中仅在呈现组件之前被调用一次。它通常用于执行初始渲染之前所需的任何状态更改,因为在此方法中调用this.setState不会触发其他渲染,因此您可以使用来更新状态
componentWillMount () { this.setState({ members : props.members }); }