繁体   English   中英

响应组件更新时设置状态的最佳方法是什么? 我的渲染方法获取更新的数据,但组件未更新

[英]what is best way to set state in react on component update? My Render method gets the updated data but component does not updates

我的订单屏幕上方有三个标签。 它的数据是这样的:

state = {
  ordersTabItems: [
    { id: 2, name: 'Incoming', isSelected: false, itemsCount: null },
    { id: 3, name: 'Processing', isSelected: false, itemsCount: null },
    { id: 4, name: 'Completed', isSelected: false, itemsCount: null },
  ],
  activeTab: 'incomming',
  inc: '',
};

我在我的render方法中使用平面列表来渲染它。 在render方法中,我还从存储中获取诸如incommingCount,处理Count和CompletedCount之类的变量。 因此,一旦标签中的数据更新,每个标签的计数值就会更改。 通过在调试器上放置调试器可以看到更新了。

我想根据从redux商店收到的道具来更新我的ordersTabItems。 我不知道应该在这里选择哪种生命周期方法。

您应该使用componentWillReceiveProps生命周期,通过比较this.propsnextProps来跟踪redux存储中的道具更改。

找到更改后,请正确更新状态,这将导致重新渲染组件。 如果您提供了更详细的代码和描述,我会尽快帮助您。

更新商店后。 您可以像这样在componentWillReceiveProps中获取连接的组件中的更新的全局状态:

componentWillReceiveProps(nextProps){
  //invoke function with updated store
  //this.foo(nextProps) any method you would like to invoke and setState there

  console.log(this.props); // prevProps
  console.log(nextProps); // currentProps after updating the store
  }

您还可以使用getDerivedStateFromProps

static getDerivedStateFromProps(nextProps, prevState) {
   }

您可以创建如下函数:

const updateActiveTab = (tabId) => {
  this.setState(...this.state, activeTab: tabId)

}

然后,您可以在render()方法中调用该函数:

this.updateActiveTab(this.props.activeTabId)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM