简体   繁体   中英

React break .map() in condition rendering

How can I use break to break a .map() function when condition rendering is true ?

This is my example code

  {messages.length >= 1 ? (
   <div>
    {messages.reverse().map((e) => (
      e.senderName[0] == displayName[0] ? (<p>Status: {e.message}</p>) : null
    ))} 
   </div>
  ) : (<p>Status: Verifying...</p>)}

The problem is in messages array is gonna have a new message add every 60 second and I want to display a new message on my screen that has been add in every 60 second

Then I want to break .map() function after a new message has been add to messages array and display on my screen

What I want is like this enter image description here

But the problem is like this enter image description here

you can't use break to stop .map() method. I see that you are trying to render messages if message belongs to current user.

I can recommend you to filter the messages first, then render the filtered array with mapping. Like:

const usersMessages = messages.reverse().filter((e) => (e.senderName[0] === displayName[0]);

return (
<div>
{usersMessages.length > 0 ? (usersMessages.map(e =>{
return((<p>Status: {e.message}</p>))
})) : <p>Status: Verifying...</p>)}
</div>
)

Of course you must have a part in your code that updates the messages array and triggers a re-render when data is updated.

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