简体   繁体   中英

React directly renders array without looping

I have an array lis to which I'm pushing elements. 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.

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

The for loop runs and finishes before the component is rendered, so when it comes time to show the list, it's already filled. Using a for loop or map() makes no difference besides the fact that map() is the functional way to iterate over arrays. That said, you can use map() to render new components for every new item, like so:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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