首页 > 解决方案 > 为什么我在道具更改后得到旧的状态值

问题描述

我只是想了解为什么在应用程序中我有以下情况,下面是我的类组件构造函数:

  constructor(props) {
    super(props);
    this.state = {
      tableAlerts: props.householdAlerts,
      initialAlerts: props.householdAlerts
    }

    console.log('householdAlerts', props.householdAlerts)
  }

在渲染功能中我有:

const { householdAlerts } = this.props;

我的问题是在构造函数中我得到了空数组,但在render函数中我有数据。是否可以在构造函数中获取数据?

标签: javascriptreactjsreact-props

解决方案


在使用类组件时,这是一个非常糟糕的模式。当您将值复制到状态时,您将忽略任何道具更新。管理它:

  1. 它要求您管理同一变量的两个数据源:状态和道具。因此,您需要在每次 prop 更改时通过将其设置为 state 来添加另一个渲染(不要忘记测试 prev 和 next 值的相等性以避免陷入无限循环)。

  2. getderivedstatefromprops您可以使用生命周期方法避免每次道具更改时设置状态。

所以建议是:just use the props; do not copy props into state

要了解更多为什么不应该这样做,我强烈推荐这篇文章


推荐阅读