You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将字符串作为属性名传入以调用JavaScript的map函数

解决方案

你当前代码的问题在于使用了点语法访问对象属性:skillSetData.pathstring是在查找skillSetData中名为pathstring的属性,而非变量pathstring的值(也就是"content"),所以无法正确获取到要遍历的数组。

要实现通过字符串变量访问对象属性并调用map,需要改用方括号语法,方括号支持传入字符串变量来定位对象属性。修正后的代码如下:

const pathstring = this.props.path; // 值为字符串"content"
// 用方括号语法获取目标数组
const targetArray = skillSetData[pathstring];
// 先判断数组是否存在,避免调用map时出现报错
const block = targetArray ? targetArray.map((data, index) => {
  return (
    <div key={index}>
      <h3>{data.url}</h3>
    </div>
  )
}) : null;

额外注意事项

  • 务必给map返回的每个元素添加key属性,这是React的强制要求,能避免渲染警告。
  • 增加数组存在性判断(targetArray ? ... : null),可以防止因属性名错误、数据未加载等情况导致的Cannot read property 'map' of undefined报错。

内容的提问来源于stack exchange,提问作者Jacklyn N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 10:25:09