首页 > 解决方案 > 在 React 中将数组转换为组件

问题描述

在项目中有一个用于填充面包屑的对象数组:

 export const BREADCRUMBS_LIST = [
   { label: 'Home', path: '/', active: false },
   { label: 'Account', path: '/accounts', active: false },
   { label: 'This Account', path: '/accounts', active: true }
 ];

它用于填充 Breadcrumbs 组件中的列表:

import { BREADCRUMBS_LIST } from './...'

...

<Breadcrumbs list={BREADCRUMBS_LIST} />

一切正常。

当我们需要根据用户的语言翻译这些标签时,就会出现问题。为此,我们使用react-intl.

因此,我将原始数组转换为这种形式的组件:

import { useIntl } from 'react-intl';

export const BreadcrumbsList = () => {
  const intl = useIntl();

  return [
    { label: intl.formatMessage({ id: 'Home' }), path: '/', active: false },
    {
      label: intl.formatMessage({ id: 'Account' }),
      path: '/accounts',
      active: false
    },
    {
      label: intl.formatMessage({ id: 'This Account' }),
      path: '/accounts',
      active: true
    }
  ];
};

并像这样使用它:

<Breadcrumbs list={BreadcrumbsList} />

这似乎是错误的,因为它返回一个错误说:

无法读取未定义的属性“地图”。

在该组件中,列表与 map 一起使用:{list.map(({path, label, active}, index) => {...})

任何想法如何解决这个问题?

标签: javascriptreactjsecmascript-6react-hooksreact-intl

解决方案


BreadcrumbsList实际上是一个自定义钩子,为了遵守钩子规则,您需要在组件级别调用它:

// Add "use" prefix as its a custom hook
const useBreadcrumbsList = () => {
  const intl = useIntl();

  return [
    { label: intl.formatMessage({ id: "Home" }), path: "/", active: false },
    {
      label: intl.formatMessage({ id: "Account" }),
      path: "/accounts",
      active: false,
    },
    {
      label: intl.formatMessage({ id: "This Account" }),
      path: "/accounts",
      active: true,
    },
  ];
};

// Usage
const Component = () => {
  const breadcrumbsList = useBreadcrumbsList();
  return <Breadcrumbs list={breadcrumbsList} />;
};

推荐阅读