小编典典

Reactjs-在子组件中使用setState从道具设置状态

reactjs

我有以下基于渲染下拉列表呈现用户的类。如果我选择“字母”,则将按字母顺序列出用户;当我选择“组”时,将按组顺序列出用户。

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函数中第一次那样更新状态变量。

怎么做?


阅读 333

收藏
2020-07-22

共1个答案

小编典典

componentWillMount在组件生命周期中仅在呈现组件之前被调用一次。它通常用于执行初始渲染之前所需的任何状态更改,因为在此方法中调用this.setState不会触发其他渲染,因此您可以使用来更新状态

componentWillMount ()
{

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


}
2020-07-22