javascript - React.js random name generator giving weird cycling through array on scroll -


i have random name generator supposed pull 1 name (or object) array , post when dom loads. works found out when scroll cycles through entire array it's not supposed do.

so error dom loads, 1 name (or object) pulled array , displays. when scroll continuously pulls other names , writes in dom instead.

here code that's giving me grief:

the array

const names = [   'yoda',   'jack sparrow',   'captain kirk',   'spock',   'optimus prime',   'gandalf',   'inigo montoya',   'magneto',   'tony stark',   'bilbo baggins',   'legolas',   'inspector clouseau',   'obi wan' ]; 

the generator

class container extends component {   constructor() {     super();     this.state = {};     this.getrandomname = this.getrandomname.bind(this);   }   getrandomname() {     return names[math.floor(math.random() * names.length)];   } 

where it's written in dom

<author>  {this.getrandomname()} </author> 

the error

when scroll, {this.getrandomname()} grabs new name array , writes dom. not sure why.

you should save name in state, otherwise you'll generate new name on every render:

class container extends component {   constructor() {     super();     this.state = {       name: this.getrandomname()     };   }   getrandomname() {     return names[math.floor(math.random() * names.length)];   } 

-

<author>  {this.state.name} </author> 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -