简体   繁体   中英

map function in javascript not working properly for React components

I am working on a project in ReactJs.I have an array in javascript for which the values will come from the back-end.So, the length of the array will be dynamic.So, I want my UI to change if the array elements contain the string 'No Email Alerts'. So I am writing a map on my array components and trying to render it in the following way:

 {this.state.options.map((email, i) => {
          return (
            <Something />   
                {!(email[i].includes('No Email Alerts')) ? (
                  <Some_Other_UI />
                ) :

                  null}

But, the issue I am facing now is I am not able to exclude the part which contains 'No Email Alerts' and render the different UI. I mean my

{!(email[i].includes('No Email Alerts')) ? (
                      <Some_Other_UI />
                    ) :

                      null}

is not working. What am i doing wrong? Someone please guide me.

The map parameters email and i is used for this.state.options and the i can be used for this.state.options array not just with email (you could use if email has similar indexes though). Also, you'll need to wrap them in an element or you may also use fragment :

{
 this.state.options.map((email, i, arr) => {
   return (
     <div key={email+'-'+i}>{/* provide the key as you wish */}
        <Something />   
        {!(arr[i].includes('No Email Alerts')) ? (
           <Some_Other_UI />
         ) :
        null}
     </div>
   )
}

I would also suggest to use trim and check for lower case in includes like this:

!(arr[i].trim().toLowerCase().includes('no email alerts'))

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