React/Redux: 等待reducer获取props

React/Redux: Wait for reducer to get props

我有以下用于导航的组件:

import React, { Component } from "react";
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';

class TabBar extends Component {
  constructor(props) {
    super(props);

    const noTankAvailable = this.props.tank.tankData.noAssignedTank;
    console.log("noTankAvailable", noTankAvailable);

    if (noTankAvailable === true || noTankAvailable === undefined) {
      this.tabs = [
        { label: "Registration", icon: faSimCard, url: "registration" }
      ];
    } else {
      this.tabs = [
        { label: "Status", icon: faChartBar, url: "status" },
        { label: "History", icon: faHistory, url: "history" },
        { label: "Properties", icon: faSlidersH, url: "properties" }
      ];
    }
    ...
  }
  ...
  render() {
    const { location, match } = this.props;
    const { pathname } = location;
    return (
      <div>
        <Tabs
          className="tabBar"
          contentContainerStyle={tabBarStyles.content}
          inkBarStyle={tabBarStyles.ink}
          tabItemContainerStyle={tabBarStyles.tabs}
          value={pathname}
        >
          {this.renderTabs(match)}
        </Tabs>
      </div>
    );
  }
}

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

export default connect(mapStateToProps)(TabBar);

这是我的 redux 减速器:

import {
  TANK_REQUEST,
  TANK_FAILURE,
  TANK_SUCCESS,
} from '../actions/tankActions';

const testState = {
  isLoading: false,
  currentTank: "",
  tankData: {}
};

export default (state = testState, action) => {
  switch (action.type) {
    case TANK_REQUEST:
      return Object.assign({}, state, { isLoading: true });
    case TANK_SUCCESS:
      if (action.tankData.length > 0) {
        const currentTank = action.tankData[0];
        const tankData = Object.assign({}, state.tankData, { [currentTank._id]: currentTank, isLoading: false });
        return Object.assign({}, state, { currentTank: currentTank._id, tankData });
      } else {
        const tankData = Object.assign({}, state.tankData, { noAssignedTank: true });
        return Object.assign({}, state, { tankData });
      }
    case TANK_FAILURE:
      return Object.assign({}, state, { currentTank: action.id, isLoading: false, error: action.err });
    default:
      return state
  }
}

给出了以下场景:当用户登录时,它获取一个 API 来获取(水)箱。如果用户没有指定的坦克,应用程序应该重定向到注册视图,导航应该只显示 "registration".

所以我通过一个动作获取。在我的减速器中,我检查我是否有数据,如果没有,我将添加 noAssignedTank: true 到我的状态。我现在想在我的 TabBar 组件中检查这是否属实以及 hide/show 导航链接取决于此。

我的 问题 是我需要等到 TANK_FETCHING_SUCCESS reducer 解决后才能检查 noAssignedTank 是否为真。

你可以看到第一个控制台输出是我的console.log("noTankAvailable", noTankAvailable);。所以我的 if/else 语句不起作用,因为起初它在获得值之前是 undefined

您必须使 this.tabs 成为组件的状态并在组件的生命周期方法期间更新它。

tankData 的检索已通过附加测试 (props.tank && props.tank.tankData) 得到保护。

初始状态在构造函数中使用 props 初始化。

前一个坦克的引用也保持状态(prevTanData)用于比较何时道具会改变(当商店中的异步值将被更新时,连接的组件将被redux通知并调用接下来是 getDerivedStateFromProps。

如果 prevTankDatanextProps.tank.tankData 相同,那么我们 return null 告诉 React 状态不需要改变。

请注意,对于 React < 16 的版本,您将必须使用实例方法 componentWillReceiveProps 而不是静态方法 getDerivedStateFromProps.

    class TabBar extends Component {
        constructor(props) {
            super(props);
            this.state = {
               tabs: TabBar.computeTabsFromProps(props),
               prevTankData: props.tank && props.tank.tankData,
            };
        };

        static computeTabsFromProps(props) {
            const noTankAvailable = props.tank &&
                                    props.tank.tankData &&
                                    props.tank.tankData.noAssignedTank;
            console.log("noTankAvailable", noTankAvailable);

            if (noTankAvailable === true || noTankAvailable === undefined) {
                return [
                    {
                        label: "Registration",
                        icon: faSimCard,
                        url: "registration"
                    }
                ];
            } else {
                return [
                    { label: "Status", icon: faChartBar, url: "status" },
                    { label: "History", icon: faHistory, url: "history" },
                    { label: "Properties", icon: faSlidersH, url: "properties" }
                ];
            }
        }
        static getDerivedStateFromProps(nextProps, prevState) {
            if ((nextProps.tank && nextProps.tank.tankData) !== prevState.prevTankData) {
                return {
                    prevTankData: nextProps.tank && nextProps.tank.tankData,
                    tabs: TabBar.computeTabsFromProps(nextProps),
                }
            }
            return null;
        }
        render() {
            ...
        }
    }