重新渲染后,组件未在componentWillReceiveProps中使用更新后的状态

时间:2019-06-27 16:19:33

标签: javascript reactjs state

我的组件正在重新渲染,但是没有使用任何initialState或componentWillReceiveProps(nextProps)。我想渲染我的组件并接收下一个道具。

我有一个组件,如果它与“选定键”匹配,则会突出显示菜单上的选项卡。我正在映射一些隐藏但需要的数据以及将要显示的数据。

为了隐藏第一个键,我设置了默认的selectedKey,以便它仅显示我想要显示的数据。

不幸的是,这仅在我第一次渲染组件时有效。在我将应用程序移至其他位置之后,返回到组件,它已重置为我想隐藏的数据,并且忽略了我给它的密钥。

  constructor(props: IProps) {
    super(props);
    this.properties = (Object.keys(removePrivateKey(props.stats)) as unknown) as (keyof IStat)[];
    this.state = {
      keySelected: this.properties.length > 0 ? this.properties[0] : 'site',
      search: ''
    };
  }

  componentWillReceiveProps(nextProps: IProps) {
    this.properties = (Object.keys(removePrivateKey(nextProps.stats)) as unknown) as (keyof IStat)[];
    if (this.state.keySelected === 'id') {
      this.setState({ keySelected: this.properties.length > 0 ? this.properties[0] : 'site' });
    }
  }

我只想显示属于“ site”键而不是“ id”键的数据。

0 个答案:

没有答案
相关问题