Reactjs - 在子组件中使用 setState 从道具设置状态 [英] 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/>
组件中,我从 componentWillReceiveProps()
函数中的 props.members 设置组件状态对象.
In <SortByAlphabet />
component I am setting a component state object from props.members in componentWillReceiveProps()
function.
componentWillReceiveProps = props => {
this.setState({ members : props.members });
}
当我选择分组"排序时,
组件正在卸载并且
正在安装在 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
函数在重新渲染
时不会第二次触发,因为道具没有改变.但我想更新状态变量,就像我第一次在 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 从道具设置状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!