0

I have started learning react.js recently, I was having issue understanding the map() function in JavaScript. I am providing code snippets where I am trying to iterate over the "person" component, while I am trying to output the result on the console I just observed its iterating twice but the components are displayed only once in the browser[enter image description here][1]. Can anyone tell me why its iterating twice?

//this is the state

class App extends Component {
  state = {
    persons: [
      {id:'aksjsdk',name:'ABC',age:'26'},
      {id:'aksjajsd',name:'XYZ',age:'25'},
      {id:'aksjadskjd',name:'MNO',age:'27'}
    ],
      showAllPersons: false
  }

........

  if(this.state.showAllPersons){
    persons = (
    <div>
        {
          this.state.persons.map((person,index) => {
            console.log(person);//printing twice
            return <Person
            name = {person.name}
            age = {person.age} 
            click = {this.deletePersonHandler.bind(this,index)}
            key ={person.id}/>
          })
        }
    </div>)
  }

....... //console output

Object { id: "aksjsdk", name: "ABC", age: "26" }
Object { id: "aksjajsd", name: "XYZ", age: "25" }
Object { id: "aksjadskjd", name: "MNO", age: "27" }
Object { id: "aksjsdk", name: "ABC", age: "26" }
Object { id: "aksjajsd", name: "XYZ", age: "25" }
Object { id: "aksjadskjd", name: "MNO", age: "27" }

1 Answer 1

2

Whenever a component's props or state update, the component re-renders.

Since you have a console.log statement in the render, we can assume that your component is rendering again. This is most likely due to some parent component rendering again like the moment it is mounted.

When a parents component re-renders, than all it's children (along with their children) re-render as well.

When a re-render occurs, it won't clear the console, so the console values are logged first time, then when the component gets re-rendered it logs again.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.