javascript - React Hooks:如何从对象数组中获取数据?
问题描述
我现在有包含组件和标题的对象数组我想根据 URL 参数中传递的 id 显示这些组件我可以做到这一点,如果它只是使用 find 函数的数组,不幸的是,我不知道如何做同样的事情带有一组对象,
这是我的代码的一部分
//array of objects
const templates =[
{
title: "TemplateOne",
component: TemplateOne,
},
{
title: "TemplateTwo",
component: TemplateTwo,
}]
//find the component and match the id passed in URL parameters
let SelectedComponent = templates.find(function (Component, idx) {
if (idx === Number(templateId)) {
return true;
}
return false;
});`
我显示这样的组件
<div>
<SelectedComponents />
</div>
但我收到如下错误
index.js:1 Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.
我需要更改什么才能使其按预期工作?
解决方案
在 react 中,组件名称应以 UpperLetter 开头,Array.prototype.find() 函数返回 Array 的一个元素。即 {title: 'blabla...', component: Blablaba} 所以我们需要命名为“Component”或 UpperLetter 前导变量的子组件。在这里,我们可以如下使用它。
//array of objects
const templates = [
{
title: 'TemplateOne',
component: TemplateOne,
},
{
title: 'TemplateTwo',
component: TemplateTwo,
},
];
const templateId = 4;
//find the component and match the id passed in URL parameters
const { component: Component } =
templates.find((Component, idx) => {
return idx === +templateId;
}) || {};
return <div>{Component && <Component />}</div>;
推荐阅读
- css - 旋转:abc ddeg;仅受 Firefox 支持,但添加浏览器前缀似乎也破坏了 Firefox
- next.js - nextjs:多个孩子被传递给了“x”的“href”,但只支持一个孩子
- python - 主循环运行太多次并在二十一点游戏中给出太多牌
- firebase - (RN) 可能未处理的 Promise Rejection (id: 0):推送通知
- r - 根据截止日期创建新列(来自另一列的日期)
- lambda - 是否可以为 Boost 变体容器创建 Boost multi_index MEM_FUN 密钥提取器?
- python - Pandas 有效过滤动态日期范围
- javascript - 在 Firebase v9 错误中使用 uploadString 监控上传
- javascript - 更改 html 和 CSS 中的背景颜色
- r - bnlearn 抛出变量 A 在 bnlearn 中不受支持(类型:字符)