React中如何通过动态props获取JavaScript对象嵌套值?
动态props获取嵌套对象值的问题与解决方案
问题说明
你尝试用info.${name}.title这种模板字符串拼接的方式访问嵌套对象值,这种写法完全不可行。因为JavaScript的点语法仅支持静态属性名,没法直接通过模板字符串动态生成属性名,这样写会直接触发语法错误。
解决方案
1. 改用方括号语法访问动态属性
JavaScript中访问动态属性名必须用方括号[]语法,正确的访问方式如下:
info[name].title info[name].content info[name].href
2. 优化写法:提前缓存目标对象
为了让代码更简洁,同时避免重复查找对象属性,建议在组件内先获取对应的嵌套对象,再访问其属性:
import Link from "next/link"; import { info } from "@/lib/info"; export default function Tip({ name }) { // 获取对应的数据项 const item = info[name]; // 容错处理:如果name对应的数据不存在,返回空提示 if (!item) return <div>暂无相关内容</div>; return ( <div> <div> <header> <p className="text-sky-400">{item.title}</p> </header> <div> <div className="max-w-80"> <p className="text-justify">{item.content}</p> <Link className="flex text-sky-700 pl-2 font-bold justify-end" target="_blank" href={item.href} > Read more ... </Link> </div> </div> </div > ); }
3. 必须修正的拼写错误
你的info对象里,属性名写的是acrruedinterest(多了一个r),但组件使用时传的是name="accruedinterest",这会导致找不到对应数据,需要统一拼写:
export const info = { accruedinterest: { // 去掉多余的r,与props传入的name一致 title: "accrued interest", content: "In finance, accrued interest is the interest on a bond or loan that has accumulated since the principal investment, or since the previous coupon payment if there has been one already.", href: "https://en.wikipedia.org/wiki/Accrued_interest", }, // ... 其他属性保持不变 }
4. 可选容错处理
如果不确定传入的name一定存在于info中,建议使用可选链操作符?.避免页面报错:
<p className="text-sky-400">{info[name]?.title || '默认标题'}</p>
内容的提问来源于stack exchange,提问作者Mohsin Abbas
相关产品推荐
相关产品推荐

