React嵌套features映射报错:类型无法分配给ReactNode
问题描述
我有一个prices数组,想要在React里映射渲染到页面,主数组的name、price能正常展示,但嵌套的features对象映射时出错,错误提示:Type '{ one: string; two: string; three: string; }' is not assignable to type 'ReactNode',无法正确渲染features内容。
给出的prices数组:
const prices = [ { name: "Standard", price: "149EGP", features: [ { one: "add 2500 Order Monthly", two: "Add Unlimted Products And Categories", three: "add 20 other Employees", }, ], }, { name: "Premium", price: "349EGP", features: [ { one: "add 2500 Order Monthly", two: "Add Unlimted Products And Categories", three: "add 20 other Employees", }, ], }, { name: "Enterprise", price: "499EGP", features: [ { one: "add 2500 Order Monthly", two: "Add Unlimted Products And Categories", three: "add 20 other Employees", }, ], }, ];
当前使用的映射代码片段:
const pricingCard = prices.map(({ name, price, features }) => { const featuresMap = features.map((feature) => { <> <li className='flex items-center space-x-3'> <svg className='flex-shrink-0 w-5 h-5 text-green-500 dark:text-green-400' fill='currentColor' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg'> <path fill-rule='evenodd' d='M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z' clip-rule='evenodd'></path> </svg> <span>{feature}</span> </li> ; </>; });
解决思路与修正代码
错误原因
- 直接把
feature对象塞进<span>,React无法渲染对象类型,必须提取对象里的字符串值。 features.map的箭头函数没有显式返回JSX,语法存在问题。- 每个
features数组里只有一个包含三个属性的对象,需要先提取该对象的所有值再逐个渲染。
修正后的完整代码
const PricingComponent = () => { const prices = [ { name: "Standard", price: "149EGP", features: [ { one: "add 2500 Order Monthly", two: "Add Unlimted Products And Categories", three: "add 20 other Employees", }, ], }, { name: "Premium", price: "349EGP", features: [ { one: "add 2500 Order Monthly", two: "Add Unlimted Products And Categories", three: "add 20 other Employees", }, ], }, { name: "Enterprise", price: "499EGP", features: [ { one: "add 2500 Order Monthly", two: "Add Unlimted Products And Categories", three: "add 20 other Employees", }, ], }, ]; return ( <div className="pricing-cards"> {prices.map(({ name, price, features }, index) => ( <div key={index} className="pricing-card"> <h3>{name}</h3> <p className="price">{price}</p> <ul> {/* 提取features数组中第一个对象的所有值,转为数组后映射 */} {Object.values(features[0]).map((featureText, idx) => ( <li key={idx} className='flex items-center space-x-3'> <svg className='flex-shrink-0 w-5 h-5 text-green-500 dark:text-green-400' fill='currentColor' viewBox='0 0 20 20' xmlns='http://www.w3.org/2000/svg'> <path fill-rule='evenodd' d='M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z' clip-rule='evenodd'></path> </svg> <span>{featureText}</span> </li> ))} </ul> </div> ))} </div> ); }; export default PricingComponent;
关键修正点
- 用
Object.values(features[0])将单个feature对象的属性值转为字符串数组,实现正常映射渲染。 - 给每个映射的JSX元素添加唯一
key属性,符合React渲染规范。 - 修正箭头函数语法,确保JSX被正确返回。
内容的提问来源于stack exchange,提问作者Youssef Hussein
相关产品推荐
相关产品推荐

