javascript - 在 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) => {...})
任何想法如何解决这个问题?
解决方案
您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} />;
};
推荐阅读
- mysql - 如何在sequelize中分组并获取相关数据数组
- java - 如何从Java中的函数访问变量?
- r - gsub 提取字符串
- python - 我的程序运行但我没有在控制台上收到反馈
- cuda - 分析一个CUDA矩阵加法代码,使用nvprof:代码API配置文件,内核没有
- python - Python/Pandas/Numpy 问题:如何在保留第四列名称的同时堆叠/合并三列
- perl - 在 Perl 中使用 require
- vb.net - 根据 DataGridView 单元格值更新 ComboBox 选择?
- python-3.x - 如何处理sklearn中不是整数的数据
- node.js - AWS Cognito:如何通过 Node.js 中的访问令牌删除用户?