gpt4 book ai didi

reactjs - React Native 状态变量未从 props 更新

转载 作者:行者123 更新时间:2023-12-05 07:00:56 25 4
gpt4 key购买 nike

我正在向我的类(class)传递 3 个 Prop - numLikes、id 和 userLiked,我想在任何渲染发生之前初始设置我的状态变量。理想情况下,状态变量的值应该等于它们对应的 Prop ,但事实并非如此。

这是我的代码:

export default class LikeButton2 extends Component {
constructor(props) {
super(props);
this.state = {
numLikes: props.numLikes,
id: props.id,
userLiked: props.userLiked,
isloading: true,
};
}
//....
}

我使用 React Native Debugger 检查变量值,但变量“numLikes”和“userLiked”没有得到更新。附上相同的证明:

enter image description here

我也尝试过使用扩展语法。这是我的代码:

export default class LikeButton2 extends Component {
constructor(props) {
super(props);
this.state = {
...props,
isLoading: true,
};
}
//....
}

虽然这也导致了状态变量的意外值。在 RN 调试器中证明这一点:

React Native Debugger output - 2

如何正确更新值?

最佳答案

在这个例子中,当组件被挂载显示时,state 被设置为等于 props。构造函数只在那个时候被调用。

在那之后,如果 Prop 发生变化,状态将不会更新以匹配它们。如果你想让你的状态在 props 改变时更新,你需要使用方法 ComponentDidUpdate : ComponentDidUpdate(prevProps,prevState) .

每次 Prop 或状态改变时都会调用它。然后你可以比较当前的 Prop (this.props) 和以前的 Prop (prevProps) 以相应地设置你的状态。

如果你只想按原样使用你的 Prop ,你可以使用 this.props ,它将始终反射(reflect)您赋予组件的值(value)。

如果我有<Component number={myNumber}/>在代码的某处,每次 myNumber 更改时组件都会重新呈现,并且值 this.props.myNumber in Component 将是准确的。

export default class ComponentTest extends Component {
constructor(props) {
super(props);
}
render() {
return <div>{this.props.number}</div>
}
}

关于reactjs - React Native 状态变量未从 props 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63982576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com