React - 使用相同的道具传播MapStateToProps

问题描述 投票:0回答:1

我有这个MapStateToProps:

const mapStateToProps = (state) => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;

  const ESFReport = getESFReport(state);
  const resultStatusReport = getResultStatusReport(state);

  return {
    companInfo: getCompanyInfo(state),
    companyId: getCompanyId(state),
    ...ESFReport,
    ...resultStatusReport,
    year,
    month,
  };
};

...ESFReport,...resultStatusReport,都有相同的属性:report但我需要以某种方式更改名称,因为在同一组件中我使用const { report } = this.props两次但不同的道具。

我怎样才能做到这一点? (当我只有... ESFReport,它曾经工作,但当我添加... resultStatusReport,它打破了)。

提前致谢。

javascript reactjs spread-syntax
1个回答
2
投票

如果你不需要reportESFReport对象的resultStatusReport以外的任何东西你可以做:

const mapStateToProps = (state) => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;

  const { report: ESFReport } = getESFReport(state);
  const { report: resultStatusReport } = getResultStatusReport(state);

  return {
    companInfo: getCompanyInfo(state),
    companyId: getCompanyId(state),
    ESFReport,
    resultStatusReport,
    year,
    month,
  };
};

它只是将report属性重命名为ESFReportresultStatusReport。然后你会有this.props.ESFReport,实际上是ESFReport.reportthis.props.resultStatusReport,这将是resultStatusReport.report

© www.soinside.com 2019 - 2024. All rights reserved.