简体   繁体   中英

How can I solve react array map function bug?

I'm trying to make a to-do app with react. It has basic functionalities: item adding, item removing, and complete task. In my code, functionalities working clearly but when I click the complete button, and the same time remove that item it is working buggy. Item removes but completed checkbox adding the next item.

Image Here

Code Section: App.js

import './App.css';
import Header from './components/Header'; 
import List from './components/List';
import React, { useState, useEffect } from 'react';

function App() {

  const [elements, setElements] = useState([]);

  useEffect(() => {
    console.log(elements);
  }, [elements]);

  const setElement = (element) => {
    setElements([...elements, element]);
  }

  const completeElement = (index) => {
    let array = [...elements];
    array[index].isCompleted = !array[index].isCompleted;
    setElements(array);
 }

  const deleteElement = (index) => {
    let array = [...elements];
    array.splice(index, 1);
    setElements(array);
  }

  return (
    <div className="todoapp">
      <Header save={setElement} />
      <List elements={elements} complete={completeElement} remove={deleteElement} />
    </div>
  );
}

export default App;

List.js:

{elements.map((item, index) => {
    const status = item.isCompleted ? "completed" : "";
    return(
        <li className={status}  key={index}>
            <div className="view">
                 <input className="toggle" type="checkbox" onClick={() => {complete(index)}} />
                 <label>{item.text}</label>
                 <button className="destroy" onClick={() => {remove(index)}}></button>
              </div>
          </li> 
      );
 })}

On List.js, className={status} working buggy.

Thanks for help.

Don't use index for key in your map items, use item id instead of it. It's the cause of problem

You can read here why do we need keys in Reac lists https://adhithiravi.medium.com/why-do-i-need-keys-in-react-lists-dbb522188bbb

您应该添加已checked入的input

<input ... checked={item.isCompleted} />

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