首页 > 解决方案 > 执行 componentDidMount 后无法设置状态

问题描述

我的组件上有以下state变量和componentDidMount方法:

  state = {
    categorized_items: []
  }
  componentDidMount() {
    this.props.fetchItems()
    // I'm trying to do the following
    console.log('uncat_items: ', this.props.uncat_items)
    this.setState({categorized_items: this.props.uncat_items})
  }
  render () {....}

  function mapStateToProps({ items_reducer }) {
    return {
     uncat_items: items_reducer.uncat_items
    }
  }

this.props.fetchItems()action 方法获取了一些项目并更新了uncat_itemsredux 存储中的值(我可以在渲染/其他方法中看到变量的预期值,没有this.props.uncat_items任何问题)。但是,对于这种特殊情况,我需要做的是在fetchItems执行该方法并更新uncat_items商店中的 之后,我需要调用setStatecategorized_items使用uncat_items. this.setState我知道在方法中这样调用componentDidMount是不正确的,但我不知道该怎么做。如您所见,我尝试 print out this.props.uncat_items,但它返回一个空数组,即使它执行了 action 方法并在 reducer 中正确更新。有人可以给我一个想法如何以正确的方式做吗?基本上,之后componentDidMount执行时,使用更新后的 redux 存储中的特定变量设置状态。

标签: javascriptreactjsasynchronousreduxreact-redux

解决方案


您的代码中的问题是您调用了一个异步操作 ( this.props.fetchItems()),然后立即调用this.setState()- 这发生在fetchItems请求完成之前(因此,在props.uncat_items填充之前)。

假设您使用的是最新的 React,根据您的特定用例,您可以:

1)丢弃状态,直接this.props.uncat_items在渲染函数中使用。

2)static getDerivedStateFromProps由于新的道具而用于更新状态。

然而,正如文档中提到的,它并不是真正推荐的,因为大多数情况可以以不同的方式处理(例如,通过切换到受控组件,如解决方案 #1 中所述)。可以在本文中找到更长的描述,文档中也提到了该描述。


推荐阅读