reactjs - React Native 状态变量未从道具更新
问题描述
我将 3 个道具 - numLikes、id 和 userLiked 传递给我的班级,我想在任何渲染发生之前首先设置我的状态变量。理想情况下,状态变量的值应该等于它们的 props 对应值,但事实并非如此。
这是我的代码:
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”没有得到更新。附上相同的证明:
我也尝试使用传播语法。这是我的代码:
export default class LikeButton2 extends Component {
constructor(props) {
super(props);
this.state = {
...props,
isLoading: true,
};
}
//....
}
尽管这也导致状态变量的值不理想。RN Debugger 中的证明:
如何正确更新值?
解决方案
在这个例子中,当组件被挂载显示时,状态被设置为等于props。构造函数只在那个时候被调用。
之后,如果道具发生变化,状态将不会更新以匹配它们。如果您希望在道具更改时更新您的状态,则需要使用方法ComponentDidUpdate : ComponentDidUpdate(prevProps,prevState)
。
每次道具或状态发生变化时都会调用它。然后,您可以比较当前的 props (this.props) 和以前的 props (prevProps) 以相应地设置您的状态。
如果您只想按原样使用您的道具,您可以直接使用this.props
,它将始终反映您赋予组件的价值。
如果<Component number={myNumber}/>
代码中有某处,则每次 myNumber 更改时,Component 都会重新渲染,并且this.props.myNumber
Component 中的值将是准确的。
export default class ComponentTest extends Component {
constructor(props) {
super(props);
}
render() {
return <div>{this.props.number}</div>
}
}
推荐阅读
- c# - 在 C# 中,是否可以有单独的路由器和控制器?
- pytorch-lightning - Pytorch Lightning limit_val_batches 和 val_check_interval 行为
- web - 阅读 PowerBi 中的 Web 服务器完整目录
- r - 如何用现有字符替换 R 中字符串中的特定字符?
- asp.net-core - 如何将 LinqExpression 转换为 OData 查询 URI
- sql - 我在查询中的加入未正确通过
- ruby-on-rails - 简单表单不保存嵌套属性
- python - 使用 vs 代码导入键盘时遇到问题
- ios - 如何解码这个特定的 JSON 模型?
- rust - 将数组、切片或向量转换为 base58 编码 WITH 检查