Reactjs - 使用子组件中的setState从props设置State [英] Reactjs - Setting State from props using setState in child component
问题描述
我有以下类根据排序下拉列表呈现用户。如果我选择按字母顺序,则按字母顺序列出用户,当我选择组时,用户将按组顺序列出。
I'm having the following class that renders users based on a sort dropdown. Users will be listed in alphabetical order if i choose "alphabetical" and in group order when i choose "group".
render(){
return(
const {members, sort} = this.state
{ sort === "alphabetical" && <SortByAlphabet members={members} /> }
{ sort === "group" && <SortByGroup members={members}/> }
)
)
在< SortByAlphabet />
组件中我从props.members设置组件状态对象 componentWillReceiveProps()
function。
In <SortByAlphabet />
component I am setting a component state object from props.members in componentWillReceiveProps()
function.
componentWillReceiveProps = props => {
this.setState({ members : props.members });
}
当我选择group排序时,< SortByAlphabet />
组件正在卸载,< SortByGroup />
正在DOM中安装。再次当我切换回按字母顺序排序时,在< SortByAlphabet />
组件中设置的状态变量(成员)变为NULL,因为组件已从DOM。
When I choose "group" sort, <SortByAlphabet />
component is unmounting and <SortByGroup />
is mounting in the DOM. Again when i switch back to "alphabetical" sort, the state variable (members) that was set previosly in <SortByAlphabet />
component becomes NULL because the component was removed from the DOM.
componentWillReceiveProps
重新渲染时,第二次触发函数< SortByAlphabet / >
b'coz道具没有变化。但我想更新状态变量,就像我第一次在 componentWillReceiveProps
函数中做的那样。
componentWillReceiveProps
function is not triggering the second time when re-rendering <SortByAlphabet />
b'coz the props didn't change. But i want to update the state variable like i did it for the first time in componentWillReceiveProps
function.
怎么做?
推荐答案
componentWillMount只调用一次在组件生命周期中,紧接在呈现组件之前。它通常用于执行初始渲染之前所需的任何状态更改,因为在此方法中调用this.setState将不会触发额外的渲染
因此您可以使用
componentWillMount is called only once in the component lifecycle, immediately before the component is rendered. It is usually used to perform any state changes needed before the initial render, because calling this.setState in this method will not trigger an additional render So you can update your staate using
componentWillMount ()
{
this.setState({ members : props.members });
}
这篇关于Reactjs - 使用子组件中的setState从props设置State的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!