显示其选项卡的图标

时间:2016-10-15 09:50:13

标签: javascript loops reactjs redux react-redux

我有一个tab的api,它有tab的名称,tab的id和图标的id(它是一个外键)。我想显示其标签的图标但是我怎样才能显示api何时以这种方式设计。

API /标签

[
{
    "id": 114,
    "name": "analytics",
    "icon": 2,
},
{
    "id": 127,
    "name": "share",
    "icon": 2,
}

API /图标

[
    {
        "id": 1,
        "name": "computer",
    },
    {
        "id": 2,
        "name": "insert-photo",
    },
    {
        "id": 3,
        "name": "account-circle",
    }
]

header.js

componentDidMount() {
      this.props.fetchTabs();
  }

  render() {
    const tabs = _.map(this.props.tabs.tabs, (tab) =>
          <span className="tab" key={tab.id}>
            <a href="">{tab.name}</a>
          </span>
    );

const mapStateToProps = (state) => ({
    fetchIcon: state.fetchIcon,
    tabs: state.tabs,
});

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    fetchTabs,
  }, dispatch);
}

帮助我了解如何显示标签的图标,因为它们与ID链接?

错误截图

使用时

const mapStateToProps = (state) => ({
    fetchIcon: state.fetchIcon,
    tabs: state.tabs.map(tab => ({
        ...tab, icon: state.fetchIcon.find(icon =>
            icon.id === tab.icon)
        ).name
    }),
    tabsPost: state.tabsPost
});

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以取消标准化mapStateToProps中的数据:

const mapStateToProps = state => ({
    tabs: state.tabs.map(tab => ({
        ...tab,
        icon: state.icons.find(icon => 
            icon.id === tab.icon
        ).name
    })
})

现在tab.icon将在您的组件中为computerinsert-photoaccount-circle

编辑:经过讨论,我们提出了以下代码:

const mapStateToProps = state => {
    return {
        tabs: state.tabs.tabs.map(tab => {
            const icon = state.deviceEventOption.find(icon => Number(icon.id) === tab.icon);
            return {
                ...tab,
                icon: icon && icon.name
            };
        })
    };
};