【问题标题】:React Hooks: How to get data from array of objects?React Hooks:如何从对象数组中获取数据?
【发布时间】:2021-06-10 00:44:25
【问题描述】:

我现在有一个包含组件和标题的对象数组对一组对象做同样的事情,

这是我的部分代码

  //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.

我需要进行哪些更改才能使其按预期工作?

【问题讨论】:

    标签: javascript arrays reactjs react-hooks


    【解决方案1】:

    在react中,组件的名字应该以UpperLetter开头,Array.prototype.find()函数返回Array的一个元素。 即{标题:'blabla ...',组件: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>;
    

    【讨论】:

    • 感谢您的解释和解决方案,它也因为它有用而受到好评
    • 您应该在return false; 行下方的行尾添加?? {},因为如果没有找到元素,Array.prototype.find 将返回undefined,并尝试从undefined 解构引发错误。破坏不在对象中的属性不会引发错误,因此使用空合并运算符 (??) 可以解决此问题
    【解决方案2】:

    SelectedComponent 的值将是一个具有titlecomponent 属性的对象。您只需渲染组件,如果您愿意,也可以传入 title 属性。

    //array of objects
    const templates = [{
        title: "TemplateOne",
        component: TemplateOne,
    }, {
        title: "TemplateTwo",
        component: TemplateTwo,
    }]
    
    //find the component and match the id passed in URL parameters
    const {component: SelectedComponent, title} = templates.find(function(Component, idx) {
        if (idx === Number(templateId)) {
            return true;
        }
        return false;
    }) ?? {};
    
    return (<div>
      {SelectedComponent && <SelectedComponent title={title} />} {/* Or don't include the title prop if you don't need to */}
    </div>);
    

    【讨论】:

    • 如果在 url 中输入了无效的 templateId,就会出现问题
    • 是的,templateId不匹配idx时需要处理验证
    • @charlietfl 已修复为 &amp;&amp;
    • 谢谢,它现在工作没有错误,并且组件按预期显示,我会接受它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 2021-09-13
    • 1970-01-01
    • 2020-09-18
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多