javascript - 执行componentDidMount后无法设置状态

标签 javascript reactjs asynchronous redux react-redux

我有以下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()操作方法获取多个项目并更新 uncat_items在 redux 存储中就好了(我可以在渲染/其他方法中看到 this.props.uncat_items 变量的预期值,没有任何问题)。但是,我需要针对此特殊情况执行的操作是在 fetchItems 之后。方法被执行并更新 uncat_items在商店,我需要调用setState并更新categorized_items处于 uncat_items 的状态。我知道打电话this.setState就像这样componentDidMount方法不正确,但我不知道该怎么做。正如你所看到的,我尝试打印出 this.props.uncat_items ,但它返回一个空数组,即使它执行了操作方法并在 reducer 中正确更新。有人可以告诉我如何以正确的方式做到这一点吗?基本上,在componentDidMount之后执行时,使用更新后的 redux 存储中的特定变量设置状态。

最佳答案

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

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

1) 删除状态并直接在渲染函数中使用 this.props.uncat_items

2) 使用static getDerivedStateFromProps 更新由于新 Prop 而产生的状态。

但是,如 the docs 中所述,实际上并不建议这样做,因为大多数情况都可以以不同的方式处理(例如,通过切换到受控组件,如解决方案 #1 中所述)。更长的描述可以在 this article 中找到。 ,文档中也提到了。

关于javascript - 执行componentDidMount后无法设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52881860/

相关文章:

javascript - 如何在 Jasmine/Maven 自动生成的 Manual SpecRunner.html 中配置我的 javascript 文件的路径?

javascript - 从 UI 触发批处理文件

javascript - React - 具有意外返回顺序的异步调用

c# - andcontinue() - 作为异步操作执行的方法

javascript - 将文本框的值传递到另一个页面 html

javascript - 查找日期列表中最早的日期

javascript - 'e' 的值可能在 IE 8 及更早版本中被覆盖

javascript - 预期数组但在 Jest 中收到数组

javascript - React.js 组件中 websocket 的 onopen 事件中调用函数

asynchronous - 如何等待 Rust 中的异步函数调用列表?