【问题标题】:connect in redux without any mapstatetoprops and still getting things as props在没有任何 mapstatetoprops 的情况下连接 redux 并且仍然将东西作为道具
【发布时间】:2019-07-31 20:56:03
【问题描述】:

我在 redux 中看到了这种奇怪的连接方式,我很难理解正在做什么以及如何做。 这是连接代码

export default connect(({ cricketFantasy: { matchDetails } }) => {
  let innings = [];
  let matchInfo = null;
  let currentOver = -1;
  let currentPlayer1Id = null;

  if (matchDetails && Object.keys(matchDetails).length) {
    const {
      homeTeam,
      awayTeam,
      tournament,
      gameDateTime,
      matchDescription,
      venue,
      currentInning,
      officials,
      squad,
      toss,
      matchState
    } = matchDetails;
    if (homeTeam && homeTeam.innings && homeTeam.innings.length) {
      homeTeam.innings.forEach(inning => {
        innings.push({
          order: inning.order,
          battingTeamName: inning.battingTeam,
          isCurrentInning: inning.id === currentInning.id
        });
      });
    }
   // some more operations which i deleted as that is not major concern 
  return {
    innings,
    matchInfo,
    currentOver,
    currentPlayer1Id,
    currentPlayer2Id,
    tournamentId,
    squad: squadObj,
    matchState: matchStateStr,
    isFetchingMatchDetail: false,
    routes,
    detailsData: matchDetails
  };
})(withStyles(styles)(withLocale(CricketScore)));

我尝试在组件的渲染方法中进行控制台登录,我看到返回的任何内容都可以视为道具。但是,我担心的是来自 ({ cricketFantasy: { matchDetails } }) 这来自。我不在此代码所在的 .js 文件中的任何位置都看不到 cricketFantasy 一词。 我也没有看到任何 mapStateToProps 。

【问题讨论】:

  • 作为参数传递给connect的函数是mapStateToProps
  • 但是条款 ({ cricketFantasy: { matchDetails } 来自哪里?你能把它分成小部分吗?
  • 它来自你的 redux 存储: const mapStateToProps = state => // state = { cricketFantasy: { matchDetails } }

标签: javascript reactjs redux react-redux


【解决方案1】:

{ cricketFantasy: { matchDetails } }destructuring assignment

它依赖于包含cricketFantasy 属性的state,其值是具有matchDetails 属性的对象。

基本上它只是一种花哨的形式:

const matchDetails = state.cricketFantasy.matchDetails;

const { matchDetails } = state.cricketFantasy;

const mapStateToProps = ({ cricketFantasy: { matchDetails } }) =>
  console.log({ matchDetails });

const state = {
  cricketFantasy: {
    matchDetails: "Hello"
  }
};

const mapStateToProps2 = (state) => {
  const matchDetails = state.cricketFantasy.matchDetails;
  console.log({ matchDetails });
};

mapStateToProps(state);
mapStateToProps2(state);

【讨论】:

    猜你喜欢
    • 2013-03-15
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 2015-02-26
    • 2020-06-26
    • 2019-04-01
    • 2015-06-06
    相关资源
    最近更新 更多