简体   繁体   English

React 直接渲染数组而不循环

[英]React directly renders array without looping

I have an array lis to which I'm pushing elements.我有一个数组lis我正在向其中推送元素。 When I render this array, react somehow renders the whole array.当我渲染这个数组时,反应会以某种方式渲染整个数组。 I thought I need to use map() for looping but it somehow rendered the array without the need to use any loops.我以为我需要使用map()进行循环,但它以某种方式呈现了数组,而无需使用任何循环。

Can you please help me with this?你能帮我解决这个问题吗?

export default function App() {
  const lis = [];
  for (let i = 0; i < 5; i++) {
    lis.push(i + 1);
  }

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      {/* thought of using this
      {lis.map(k => k)}   */} //Output : 12345
      {/* but this worked too... why ?? */}
      {lis}        //Output : 12345
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Please visit CodeSandbox 请访问 CodeSandbox

The for loop runs and finishes before the component is rendered, so when it comes time to show the list, it's already filled. for 循环在渲染组件之前运行并完成,因此当需要显示列表时,它已经被填充了。 Using a for loop or map() makes no difference besides the fact that map() is the functional way to iterate over arrays.除了map()是迭代 arrays 的功能性方式之外,使用 for 循环或map()没有任何区别。 That said, you can use map() to render new components for every new item, like so:也就是说,您可以使用map()为每个新项目呈现新组件,如下所示:

import "./styles.css";

export default function App() {
  const lis = [];
  for (let i = 0; i < 5; i++) {
    lis.push(i + 1);
  }

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      
      {/* for every item in the array, render a new <p> element */}
      {lis.map((k) => <p key={k}>{k}</p>)}

      {console.log(lis)}
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Note that in cases like that where you'll render a list of components, you have to add a key property or React will scream at you.请注意,在您将呈现组件列表的情况下,您必须添加一个关键属性,否则 React 会尖叫您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM