typescript 如何在react中接收对象

k5ifujac  于 2023-11-20  发布在  TypeScript
关注(0)|答案(1)|浏览(142)

当我尝试在组件中接收对象时,出现错误。
在console log“react-dom.development.js:14887 Uncaught Error:Objects are not valid as a React child(found:object with keys {id,url,icon}).如果你想呈现一个子对象的集合,请使用数组。”this is data component when some id, url, ann icon I can't pass those data to Navbar component

export const social = [
  {
   id: 1,
   url: 'https://www.twitter.com',
   icon: <FaTwitter />,
  },
  {
   id: 2,
   url: 'https://www.facebook.com',
   icon: <FaFacebook />,
  },
  {
   id: 3,
   url: 'https://www.linkein.com',
   icon: <FaLinkedin />,
  },
  {
   id: 4,
   url: 'https://www.youtube.com',
   icon: <FaYoutube />,
  },
];

字符串
I added some data in the data component in console there showing Objects are not valid as a React child (found: object with keys {id, url, icon})

import React from 'react';
import { social } from './data';
const Navbar = () => {
  console.log(social);
  return (
    <nav>
      <div>
        {social.map((item: any, index) => {
          return <li key={index}>{item}</li>;
        })}
      </div>
    </nav>
  );
};
export default Navbar;


but without typescript variant I can receive all those data

dl5txlt9

dl5txlt91#

你不能在JSX中渲染原始对象,你必须以某种方式塑造它们,例如:

type Social = {
  id: number;
  url: string;
  icon: ReactNode;
}

const Navbar = () => {
  return (
    <nav>
      {social.map(({ id, url, icon }: Social) => (
        <li key={id}>
          <a href={url}>{icon}</a>
        </li>
      ))}
    </nav>
  );
};

字符串

相关问题