【问题标题】:Redux Thunk Async React Component Did mountRedux Thunk Async React 组件是否挂载
【发布时间】:2018-05-04 13:13:09
【问题描述】:

componentDidMount() {
    this.props.fetchAccountData();
}
render() {
    const { accounts  } = this.props.accountData;
    policyDetailsInfo =  accounts[0].policy_summary;
    accountDetails = accounts[0];
    return (
      <div>
        <Account
          accountDetails={accountDetails}
          policyDetails={policyDetailsInfo}
        />
      </div>
    )
}

const mapStateToProps = state => ({
  accountData: state.accountData
});

const mapDispatchToProps = {
  fetchAccountData
};

export default connect(mapStateToProps, mapDispatchToProps)(AccountHome);
  1. 这里进入componentDidMount的fetchAccountData方法是 异步调用。
  2. 这里我想当 fetchAccountData 响应得到 之后,只有控制进入渲染方法。这里会这样 多次进入渲染方法,直到异步调用方法得到 回复。
  3. 由于此控件进入子组件,而该组件确实 没有得到响应后可能会填充的属性 来自异步调用。

问候,

【问题讨论】:

    标签: redux react-redux redux-thunk


    【解决方案1】:

    如果你正确配置了reducer,每当异步调用响应到达时,render()方法AccountHome组件将被触发(因为accountData发生了变化,AccountHome注册到的状态)

    const mapStateToProps = state => ({
      accountData: state.accountData
    })
    

    您有很多方法可以编写逻辑来处理 accountData,但为了简单起见并专注于您粘贴的代码,请更新 render() 方法并使其了解 accountData prop

    render() {
      const accounts = this.props.accountData;
      if(!accounts || !accounts.length ) {
        // set a simple loading solution
        // avoid errors using empty accounts
        return (
          <div>
            Loading content...
          </div>
        }
      }
    
      // here accounts has data inside
      const policyDetailsInfo =  accounts[0].policy_summary;
      const accountDetails = accounts[0];
    
      return (
        <div>
          <Account
            accountDetails={accountDetails}
            policyDetails={policyDetailsInfo}
          />
        </div>
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-09
      • 2021-12-08
      • 2022-12-21
      • 2019-02-02
      • 2019-04-20
      • 2018-10-10
      • 2018-05-19
      • 2018-07-22
      • 2018-01-31
      相关资源
      最近更新 更多