reactjs; after mapping an array nothing renders

一笑奈何 提交于 2019-12-01 11:48:30

You will need to return a value from your function like so:

   mapArrayToButtons(){
        return this.state.textArr.map((word)=>{
            return(<button key={word} type="button" className="btn btn-default" value={word}>{word}</button>);});
    }

Hope that helps!

There are 2 things you need to know / be aware of :

1 - If you have an array of jsx , for instance :

let arrayOfJsx = [ <div>Hello</div>, <div>World</div> ] 

When you put this array in your render method , like :

render(){

   let arrayOfJsx = [ <div>Hello</div>, <div>World</div> ] 

   return (
      <div> { arrayOfJsx } </div>
   )
}

is equivalent to

render(){

       return (
          <div>
               <div>Hello</div>
               <div>World</div> 
          </div>
       )
}

2 - Diffence between Array.prototype.forEach and Array.prototype.map :

When you use forEach, what you return from the function you are passing to forEach is not important, it is only important to know that the function stops executing when you return a value, this is not special to forEach. But when we say what you return is not important we want to point out how what you return is important for Array.prototype.map :

You want to use map when you want to create an array from what you return for each item in an array.

Example :

let a = [ 1,2,3 ]
let b = a.map( item => item + 1 )
// b is now [ 2,3,4 ]

To sum up, what you want to do in your example create an array from map and put it in your render method. If you don ' t know about these 2 points, you won't be understanding how it works.

NOTE : you need to pass a unique key for each item you return in your map function. For instance :

let a = [ 1,2,3 ]
let arrayOfJsx = a.map( item => <div key={item} > I am { item } </div> )

So that react doesn t complain

try this

mapArrayToButtons(){
    const buttons = this.state.textArr.map((word)=>{
        console.log('the word: ',word);
        return(<button key={word} type="button" className="btn btn-default" value={word}>{word}</button>);});
    return buttons;

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!