reactjs 如何在JSX中从项目数组中输出项目?

tf7tbtn2  于 2023-04-11  发布在  React
关注(0)|答案(4)|浏览(229)

我有一个类似的小数组
const arr = [{ "0": "First Item", "1": "Second Item", "2": "Third Item"}]
我想在JSX中输出它。
这就是我的https://codesandbox.io/s/focused-bose-wgmbny?file=/src/App.js。正如你所看到的,它只输出数组的第一个元素。
我试过使用forEach和for循环,但都没有用。(开发人员告诉我,应该使用.map作为JSX)
我也试过这个:

arr.map((item, index) => (
    <p>{item[index]}</p>
))

我只想让map输出:
“第一项”“第二项”“第三项”
但它只停留在“第一项”

zxlwwiss

zxlwwiss1#

@steve这里要考虑多点
1.你的数组包含一个对象,所以数组的长度是1,并且只会迭代一次。
1.在数组中,有一个对象,访问item[index]将获取对象的第一个索引,从而获取结果。

方法1

return (
    <div className="App">
      {testArry.map((item, index) => {
        const obj = Object.values(item).map(item1 => item1)
        return obj;
      })}
    </div>
  );

方法2

const testArry = ["First Iteam", "Second Item", "Third Item"];

return (
    <div className="App">
      {testArry.map((item, index) => {
        return item
      })}
    </div>
  );
}
fzwojiic

fzwojiic2#

在您示例中,数组只有1个对象
然后循环播放
而map只会循环一次,它会返回你的对象;
您的项目为**{“0”:“第一项”,“1”:“第二项”,“2”:“第三项”};
并且
index总是0**,因为它只会循环一次。
使用item[index]
这意味着你的项目是上面的对象
item[index]仅表示object的key

const arr = [{ "0": "First Item", "1": "Second Item", "2": "Third Item"}];

// here is in your array only have 1 element

//{ "0": "First Item", "1": "Second Item", "2": "Third Item"}

// and if you console it you will see that item is
// { "0": "First Item", "1": "Second Item", "2": "Third Item"}

console.log(arr[0]);
console.log(arr[0][0]);
arr.map((item, index) => {
    console.log(item[index]);
    console.log(item);
});

// so you should do
const arr1 = [{ "0": "First Item"}, {"1": "Second Item"}, {"2": "Third Item"}];

arr1.map((item, index) => {
  console.log(item[index]);
  console.log(item);
});
h22fl7wq

h22fl7wq3#

const arr = [{ "0": "First Item", "1": "Second Item", "2": "Third Item"}]

它是一个数组,有一个对象作为它的元素。当你像这样在arr上使用map函数时:

arr.map((item, index) => item[index])

它迭代arr中的元素,对于每个元素(在本例中是单个对象),它返回带有键index(当前map迭代的索引)的property。所以实际上您在这里调用arr[0][0]
正确的数组为:

const arr = ["First Item", "Second Item", "Third Item"];

然后,您可以打印每个项目:

return (
    <div className="App">{arr.map((item) => item)}</div>
  );
cgvd09ve

cgvd09ve4#

const items = ["Item 1", "Item 2", "Item 3"];

function MyComponent() {
  return (
    <div>
      {items.map((item, index) => (
        <p key={index}>{item}</p>
      ))}
    </div>
  );
}

相关问题