首页 > 解决方案 > 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.

我需要更改什么才能使其按预期工作?

标签: javascriptarraysreactjsreact-hooks

解决方案


在 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>;

推荐阅读