【问题标题】:Show icon of its tab显示其选项卡的图标
【发布时间】:2017-02-24 17:36:30
【问题描述】:

我有一个选项卡的 api,它有选项卡的名称、选项卡的 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
});

【问题讨论】:

    标签: javascript loops reactjs redux react-redux


    【解决方案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
                };
            })
        };
    };
    

    【讨论】:

    • 我在 .name 部分上收到错误作为意外令牌。 const mapStateToProps = (state) => ({ fetchIcon: state.fetchIcon, tabs: state.tabs.map(tab => ({ ...tab, icon: state.fetchIcons.find(icon => icon.id == = tab.icon) ).name }) tabsPost: state.tabsPost });
    • 这意味着它找不到具有给定 id 的图标。
    • 现在错误显示在 }) 上代码的最后一行作为意外标记。
    • 这段代码删除了错误,但得到了另一个错误 state.tabs.map is not a function 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 });
    • 我无法帮助您解决所有问题。您应该了解每条错误消息的含义。您提到的最后一个错误意味着 state.tabs 没有名为 map 的函数,这意味着它不是数组而是其他东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    相关资源
    最近更新 更多