Javascript 子组件在父组件中设置setstate时getDerivedStateFromProps出现问题
我有3个组件<代码>祖父母,Javascript 子组件在父组件中设置setstate时getDerivedStateFromProps出现问题,javascript,reactjs,Javascript,Reactjs,我有3个组件祖父母,父母和孩子。 如果祖父母中的数据更改,我将其作为道具传递给父母,这样我可以触发父母中的更改,并使用getDerivedStateFromProps将新数据设置为其状态 export class Parent extends Component { constructor(props) { super(props); this.state = { userId : this.props.userId } } static getD
父母
和孩子
。
如果祖父母
中的数据更改,我将其作为道具传递给父母
,这样我可以触发父母
中的更改,并使用getDerivedStateFromProps
将新数据设置为其状态
export class Parent extends Component {
constructor(props) {
super(props);
this.state = {
userId : this.props.userId
}
}
static getDerivedStateFromProps(nextProps, prevState) {
if(nextProps.userId !== prevState.userId)
return {
userId : this.props.userId
}
return null
}
getDataFromChild(value){
this.setState({
userId: value
})
}
render(){
return (
<Child onChange={(value) => this.getDataFromChild(value)} />
)
}
}
问题是,当父组件中的任何状态或道具发生更改时,会触发从道具中获取派生状态,因为nextprops.userId
不等于prevState
(由Child
设置的新状态),旧的userId(来自祖父母
)被设置为状态。
我该怎么办。
对不起,我的英语水平不好。如果您希望在
祖父母
中的值更改时更改父
中的状态,那么最快的方法是使用组件更新
:
export class Parent extends Component {
constructor(props) {
super(props);
this.state = {
userId : this.props.userId
}
}
getDataFromChild(value){
this.setState({
userId: value
})
}
componentDidUpdate(prevProps) {
if(prevProps.userId !== this.props.userId) {
this.setState({
userId: this.props.userId,
});
}
}
render(){
return (
<Child onChange={(value) => this.getDataFromChild(value)} />
)
}
}
相关的:
一旦
子组件在父组件中设置了状态,您不希望祖父母的状态影响它吗?不,我不希望。我希望Child
可以在Parent
中设置状态,但由于Parent
中的以下代码,状态设置为使用旧数据(来自Parent)。静态GetDerievedStateFromProps(nextProps,prevState){if(nextProps.userId!==prevState.userId)返回{userId:this.props.userId}返回null}@Agney
export class Parent extends Component {
constructor(props) {
super(props);
this.state = {
userId : this.props.userId
}
}
getDataFromChild(value){
this.setState({
userId: value
})
}
componentDidUpdate(prevProps) {
if(prevProps.userId !== this.props.userId) {
this.setState({
userId: this.props.userId,
});
}
}
render(){
return (
<Child onChange={(value) => this.getDataFromChild(value)} />
)
}
}
getDataFromChild(value){
this.setState({
userId: value,
setByChild: true,
})
}
componentDidUpdate(prevProps) {
if(!this.state.setByChild && prevProps.userId !== this.props.userId) {
this.setState({
userId: this.props.userId,
});
}
}