.map() undefined 即使我传递了一个数组

.map() undefined even though I pass an array

我试图在我的组件渲染方法中映射一个数组,但它一直显示 .map is not a function,即使它是一个数组。

return (
  <select className="c-select">
    <option value="">Choose your city</option>
      {console.log(state.cities.items)}
      {state.cities.items.map(city => <option key={city.slug} value={city.slug}>{city.name}</option>)}
  </select>
);

控制台日志给了我这个结果:

[{"id":1,"name":"Berlin","country":"Germany","default":1,"slug":"berlin"},{"id":2,"name":"Hamburg","country":"Germany","default":0,"slug":"hamburg"}]

我不知道为什么 .map 未定义 - 我在这里遗漏了什么吗?

如果您使用的是 Chrome 或 Firefox,state.cities.items 看起来像是 JSON 字符串,而不是数组。

尝试

{JSON.parse(state.cities.items).map(...)}

当你 console.log 真正的数组时,输出在 Firefox 中看起来像 Array [ Object, Object ] 或在 Chrome

中看起来像 >[Object]