簡體   English   中英

React 狀態被“損壞”

[英]React state gets "corrupted"

我正在研究一個簡單的 React.JS 前端部分。

我基本上有一個歷史數據瀏覽 SPA。 該設計有一堆過濾器,我需要一次填充一個,從我的邏輯層次結構中的頂層開始。

我做類似的事情:

  componentWillMount() {
    if (!this.props.advertisers) {
      this.props.loadAdvertisers();
    }
  }

加載廣告商數組后,我將其映射到選擇組件的選項(使用react-select ),將選擇設置為列表中的第一項並加載下一個列表 - campaigns

據我所知,最好的方法仍然是componentWillReceiveProps() ,鑒於componentWillReceiveProps正在被淘汰,我有點困惑應該如何以不同的方式完成。

我的代碼看起來像:

componentWillReceiveProps(nextProps) {
  if (nextProps.advertisers && !this.props.advertisers) {
    const advertiser = nextProps.advertisers[0];
    this.setState({
      advertiser: {
        value: advertiser['id'],
        label: advertiser['name']
      }
    });
    nextProps.loadCampaigns(advertiser['id']);
  }
  // if campaigns list changed, reload the next filtered array
  if (nextProps.campaigns && this.props.campaigns !== nextProps.campaigns) {
    ...
  }

這工作正常,直到我決定添加一個加載指示器。 我映射了狀態的loading屬性,例如,對於它通過this.props.campaignsLoading公開的campaigns ,然后執行:

return (this.props.campaignsLoading || this.props...Loading || ...) ? 
       <ProgressIndicator> : <MainContentPanel>

現在的問題是,我的狀態沒有在componentWillReceiveProps()中正確設置。

該項目正在使用@rematch ,我最初嘗試使用@rematch/loading插件進行此操作,當問題發生時,我認為插件以某種方式做錯了。 然后,我手動映射loading屬性,並添加了兩個dispatch es來手動設置加載flag

所有的道具都被正確設置/取消設置,但我的狀態沒有被設置並且沒有任何效果。 有什么建議么?

當你做

if (nextProps.advertisers && !this.props.advertisers) {

您不是在比較下一個和上一個道具。 “this.props.advertisers”可能已經設置好,因此您永遠不會進入 setState 行。 雖然使用 componentWillReceiveProps 不再是推薦的方法( 你可能不需要派生狀態),但你可能想要做的大致是:

if (nextProps.advertisers && nextProps.advertisers !== !this.props.advertisers) {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM