Recommendations list showing incorrect data after item deletion

I have a simple list of student objects named and their grades in state.

Their name is tied to <b>{student.name}</b>

, and their score is tied to

<input type="text" defaultValue={student.score}/>

      

when I want to remove the first student from this list and re-render the component by calling the set state

a second student's input tag, showing the first student's grade instead of his own. Why does this happen when I do it wrong?

here is my code here is mycode in jsbin

class App extends React.Component{
  constructor(){
    super();
    this.state ={
      students:[{name:"A",score:10},{name:"B",score:20},{name:"C",score:30}]
    }
  }

  onDelete(index){
    this.state.students.splice(index,1);
    this.setState(this.state);
  }

   render(){
     return(
       <div>
         {this.state.students.map((student,index)=>{
              return(
                <div key={index}>
                    <b>{student.name}</b> - <input type="text" defaultValue={student.score}/>
                     <button onClick={this.onDelete.bind(this,index)}>delete</button>
                </div>                
              )
         })}
       </div>
     )
   }
}


ReactDOM.render(<App/>,document.getElementById("main"));

      

+3


source to share


2 answers


This is because you are using a key={index}

student-unique value instead.

When the array is changed, students will have the wrong key after the index is deleted, and React will not register the key change for the rerender with the updated data.

Instead, you should use something like this ...



<div key={student.name}>

      

assuming it student.name

is unique.

+3


source


It is always best to use the unique identifier as a key rather than an index. If your JSON doesn't provide a unique ID, you can use something like the uuid npm module that generates one for you. This is the link https://www.npmjs.com/package/uuid .

Then you can import it and use like below

import { v4 } from 'uuid'; //there are 5 versions. You can use any.

      



then use it to generate uique id by calling v4 function like below

id={v4()}

      

+1


source







All Articles