javascript - 为什么我在道具更改后得到旧的状态值
问题描述
我只是想了解为什么在应用程序中我有以下情况,下面是我的类组件构造函数:
constructor(props) {
super(props);
this.state = {
tableAlerts: props.householdAlerts,
initialAlerts: props.householdAlerts
}
console.log('householdAlerts', props.householdAlerts)
}
在渲染功能中我有:
const { householdAlerts } = this.props;
我的问题是在构造函数中我得到了空数组,但在render
函数中我有数据。是否可以在构造函数中获取数据?
解决方案
在使用类组件时,这是一个非常糟糕的模式。当您将值复制到状态时,您将忽略任何道具更新。管理它:
它要求您管理同一变量的两个数据源:状态和道具。因此,您需要在每次 prop 更改时通过将其设置为 state 来添加另一个渲染(不要忘记测试 prev 和 next 值的相等性以避免陷入无限循环)。
getderivedstatefromprops
您可以使用生命周期方法避免每次道具更改时设置状态。
所以建议是:just use the props; do not copy props into state
。
要了解更多为什么不应该这样做,我强烈推荐这篇文章。
推荐阅读
- cordova - 浏览器中 Keycloak 服务器的 Ionic Lab 错误(拒绝构建 Kyecloak 服务器,因为祖先违反了)
- git - VSCode + Github,没有初始化存储库按钮
- ios - 即使在正确设置属性后,iOS tableViewCell 也不会在重新加载 tableview 后更新
- node.js - 将多个氦 API 调用从设备移动到服务器端
- angular - 使用 SAML 为 Angular 实施 Azure AD SSO
- nginx - proxy_pass 连接不安全
- python - 排序边界框或合并它们python
- database - Clickhouse - 100亿数据是否需要单独的数据库和表格
- python - 为什么这两个进程的行为是这样的?
- google-apps-script - Google Apps 脚本 - 在行中搜索字符串并返回匹配列的第 1 行