更改后React JS Usestate&使用效果阵列重复元素

发布于 2025-02-13 09:31:35 字数 4669 浏览 0 评论 0 原文

我是React JS编程的初学者。我正在尝试进行TODO项目,这是一个经典项目。当我删除或添加列表中的元素时,新形成的列表通过与上一个结合使用,将出现在屏幕上,我将显示下面的图片。我不了解eror的来源,因此想在此处发布它以获取一些建议,以了解它发生的原因

。状态

在数组中添加元素后。

我正在使用Usestate进行数组,并使用使用效果来获取初始数据

mainpage.js包含表单和列表组件。

const MainPage = () => {
  const [isLoading, setLoding] = useState(true);
  const [array, setArray] = useState([]);
  const sub = async (email) => {
    var result = [];
    await onSnapshot(doc(db, "users", email), (doc) => {
      var data = doc.data().todos;
      data.forEach((element) => {
        Object.keys(element).map(() => {
          result.push(element["title"]);
        });
      });
      setArray(result);
      setLoding(false);
    });
  };

  useEffect(() => {
    sub(auth.currentUser.email);
  }, []);

  const onAddToDo = (todoTitle) => {
    setArray((prevAray) => {
      return [...prevAray, todoTitle];
    });
  };
  const onRemove = (title) => {
    setArray((prevAray) => {
      return [array.pop(array.indexOf(title))];
    });
  };
  return (
    <div>
      {isLoading && <h1>Loading</h1>}
      {!isLoading && (
        <div>
          <section>
            <NavBar></NavBar>
            <ToDoForm passData={onAddToDo} />
          </section>
          <section>
            <CardList removeCards={onRemove} array={array} />
          </section>
        </div>
      )}
    </div>
  );
};

export default MainPage;

firebase.js存储firebase Update方法

export const deleteItem = (title) => {
  updateDoc(doc(db, "users", auth.currentUser.email), {
    todos: arrayRemove({ title: title }),
  });
};
export const addnewTodo = (title) => {
  updateDoc(doc(db, "users", auth.currentUser.email), {
    todos: arrayUnion({ title: title }),
  });
};

todoForm.js组件

const ToDoForm = (props) => {
  const [todoTitle, setTitle] = useState("");
  const titleChangeHandler = (event) => {
    setTitle(event.target.value);
  };
  const newTodoAdder = (event) => {
    event.preventDefault();
    addnewTodo(todoTitle);
    props.passData(todoTitle);
  };

  return (
    <div className="form_holder">
      <div className="form_container">
        <form onSubmit={newTodoAdder}>
          <h3>Add Events</h3>
          <label>Title</label>
          <input
            onChange={titleChangeHandler}
            type="text"
            placeholder="Title"
            id="title"
          ></input>
          <div className="holder">
            <button type="sumbit">Add</button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default ToDoForm;

Cardlist.js Component

const CardList = (props) => {
  const array = props.array;
  if (array.length === 0) {
    return (
      <div className="grid_container">
        <h2>Found no todos</h2>
      </div>
    );
  }

  return (
    <div className="grid_container">
      {array.map((element, index) => {
        return (
          <Card
            removeSelf={() => {
              props.removeCards(element);
            }}
            key={index}
            title={element}
          />
        );
      })}
    </div>
  );
};

export default CardList;

card.js component

const Card = (props) => {
  const handleRemove = (event) => {
    event.preventDefault();
    deleteItem(props.title);
    props.removeSelf();
  };
  return (
    <div className="card">
      <h2 className="card__title">{props.title}</h2>
      <button type="button" onClick={handleRemove}>
        Delete
      </button>
    </div>
  );
};

export default Card;

编辑;

index.js file

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { BrowserRouter } from "react-router-dom";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

I am a beginner in react js programming. I'm trying to do the todo project, which is a classic project. When I delete or add an element from the list, the newly formed list appears on the screen by combining with the previous one, I will show it with a picture below. I did not understand the source of the eror so wanted to post it here to get some advices suggestions about why it is happening.Thank you.(I am getting and storing data in firebase firestore database)

Before Adding an element initial array state
enter image description here

After adding an element to the array.
enter image description here

I am using useState for array and using useEffect to get initial data

MainPage.js that contains form and the list components.

const MainPage = () => {
  const [isLoading, setLoding] = useState(true);
  const [array, setArray] = useState([]);
  const sub = async (email) => {
    var result = [];
    await onSnapshot(doc(db, "users", email), (doc) => {
      var data = doc.data().todos;
      data.forEach((element) => {
        Object.keys(element).map(() => {
          result.push(element["title"]);
        });
      });
      setArray(result);
      setLoding(false);
    });
  };

  useEffect(() => {
    sub(auth.currentUser.email);
  }, []);

  const onAddToDo = (todoTitle) => {
    setArray((prevAray) => {
      return [...prevAray, todoTitle];
    });
  };
  const onRemove = (title) => {
    setArray((prevAray) => {
      return [array.pop(array.indexOf(title))];
    });
  };
  return (
    <div>
      {isLoading && <h1>Loading</h1>}
      {!isLoading && (
        <div>
          <section>
            <NavBar></NavBar>
            <ToDoForm passData={onAddToDo} />
          </section>
          <section>
            <CardList removeCards={onRemove} array={array} />
          </section>
        </div>
      )}
    </div>
  );
};

export default MainPage;

Firebase.js that stores the firebase update methods

export const deleteItem = (title) => {
  updateDoc(doc(db, "users", auth.currentUser.email), {
    todos: arrayRemove({ title: title }),
  });
};
export const addnewTodo = (title) => {
  updateDoc(doc(db, "users", auth.currentUser.email), {
    todos: arrayUnion({ title: title }),
  });
};

TodoForm.js component

const ToDoForm = (props) => {
  const [todoTitle, setTitle] = useState("");
  const titleChangeHandler = (event) => {
    setTitle(event.target.value);
  };
  const newTodoAdder = (event) => {
    event.preventDefault();
    addnewTodo(todoTitle);
    props.passData(todoTitle);
  };

  return (
    <div className="form_holder">
      <div className="form_container">
        <form onSubmit={newTodoAdder}>
          <h3>Add Events</h3>
          <label>Title</label>
          <input
            onChange={titleChangeHandler}
            type="text"
            placeholder="Title"
            id="title"
          ></input>
          <div className="holder">
            <button type="sumbit">Add</button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default ToDoForm;

CardList.js component

const CardList = (props) => {
  const array = props.array;
  if (array.length === 0) {
    return (
      <div className="grid_container">
        <h2>Found no todos</h2>
      </div>
    );
  }

  return (
    <div className="grid_container">
      {array.map((element, index) => {
        return (
          <Card
            removeSelf={() => {
              props.removeCards(element);
            }}
            key={index}
            title={element}
          />
        );
      })}
    </div>
  );
};

export default CardList;

Card.js component

const Card = (props) => {
  const handleRemove = (event) => {
    event.preventDefault();
    deleteItem(props.title);
    props.removeSelf();
  };
  return (
    <div className="card">
      <h2 className="card__title">{props.title}</h2>
      <button type="button" onClick={handleRemove}>
        Delete
      </button>
    </div>
  );
};

export default Card;

EDIT ;

Index.js file

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { BrowserRouter } from "react-router-dom";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

翻身的咸鱼 2025-02-20 09:31:35

解决方案

我通过更改mainpage.js文件中的添加和删除功能来解决问题,您可以看到新版本的bellow。希望有一天它将对某人有所帮助。
使用效果是在更改后我必须再次获取数据的所有方法...

新删除并添加功能

const onAddToDo = (todoTitle) => {
    console.log(todoTitle + " Added");
    sub(auth.currentUser.email);
  };
  const onRemove = (title) => {
    console.log(title + " Deleted");
    sub(auth.currentUser.email);
  };

SOLUTION

I fixed the issue by changing the add and remove functions that were inside of MainPage.js file You can see the new versions bellow. Hope someday it will help somebody.
Use effect was called once all I had to do get the data again after a change...

New Remove and Add functions

const onAddToDo = (todoTitle) => {
    console.log(todoTitle + " Added");
    sub(auth.currentUser.email);
  };
  const onRemove = (title) => {
    console.log(title + " Deleted");
    sub(auth.currentUser.email);
  };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文