简体   繁体   English

当我第一次点击删除按钮时,所有的笔记都消失了,但是当我刷新页面时它工作得很好

[英]When I first click the delete button, all the notes are disappeared but, when I refresh the page it works just fine

I tried almost everything.我几乎尝试了所有方法。 I tested my API to ensure that the problem is not with it.我测试了我的 API 以确保问题不在于它。 It happens just one time when you visit the page.当您访问该页面时,它只会发生一次。 However, when you refresh it works fine.但是,当您刷新时它工作正常。

Before Clicking delete: Click here to see the image单击删除之前:单击此处查看图像

After clicking delete button: Click here to see the image单击删除按钮后:单击此处查看图像

Backend Route (home.route.js):后端路由(home.route.js):

const express = require("express");
const mongoose = require("mongoose");
const Note = require("../models/note.model.js");
const router = express.Router();

router.get("/", (req, res) => {
    Note.find()
        .then(notes => res.json(notes))
        .catch(err => res.status(400).json("Error: " + err));
});

router.post("/", (req, res) => {
    const note = req.body;
    const newNote = new Note(note);

    newNote.save()
        .then(() => res.json("Note added"))
        .catch(err => res.status(400).json("Error: " + err));
});

router.delete("/", (req, res) => {
    const idWeGotFromReact = req.body.noteId;
    Note.findByIdAndDelete(idWeGotFromReact)
        .then(() => res.json('Note deleted.'))
        .catch(err => res.status(400).json('Error: ' + err));
})

module.exports = router;

React Code:反应代码:

Code for the Note Component: Note 组件的代码:

import React from "react";
import axios from 'axios';
import DeleteIcon from '@material-ui/icons/Delete';

function Note(props) {
  function handleClick() {
    const id = props.noteId;
    axios({
      method: 'delete',
      url: 'http://localhost:5000',
      data: {
        noteId: id
      }
    });
    props.onDelete(id);
  }

  return (
    <div className="note">
      <h1>{props.title}</h1>
      <p>{props.content}</p>
      <button name={props.noteId} onClick={handleClick}>
        <DeleteIcon />
      </button>
    </div>
  );
}

export default Note;

Code for the Main App component: Main App 组件的代码:

import React, { useState, useEffect } from "react";
import axios from "axios";
import Header from "./Header";
import Footer from "./Footer";
import Note from "./Note";
import CreateArea from "./CreateArea";

function App() {
  const [notes, setNotes] = useState([]);

  useEffect(() => {
    axios
      .get('http://localhost:5000')
      .then(res => {
        setNotes(res.data);
      });
  }, []);


  function addNote(newNote) {
    setNotes(prevNotes => {
      return [...prevNotes, newNote];
    });
  }


  function deleteNote(id) {
    setNotes(notes => {
      return notes.filter((noteItem) => {
        return noteItem._id !== id;
      });
    });
  }

  function NoteList() {
    return (
      notes.map((noteItem) => {
        return (
          <Note
            key={noteItem._id}
            id={noteItem._id}
            title={noteItem.title}
            content={noteItem.content}
            onDelete={deleteNote}
            noteId={noteItem._id}
          />
        );
      })
    );
  }

  return (
    <div>
      <Header />
      <CreateArea onAdd={addNote} />
      <NoteList />
      <Footer />
    </div>
  );
}

export default App;

Input Component:输入组件:

import React, { useState } from "react";
import axios from "axios";

function CreateArea(props) {
  const [note, setNote] = useState({
    title: "",
    content: ""
  });

  function handleChange(event) {
    const { name, value } = event.target;

    setNote(prevNote => {
      return {
        ...prevNote,
        [name]: value
      };
    });
  }

  function submitNote(event) {
    props.onAdd(note);
    setNote({
      title: "",
      content: ""
    });

    event.preventDefault();

    axios
      .post('http://localhost:5000', note)
      .then(res => {
        console.log(res);
        console.log(res.data);
      });
  }

  return (
    <div>
      <form action="/" method="post">
        <input
          name="title"
          onChange={handleChange}
          value={note.title}
          placeholder="Title"
        />
        <textarea
          name="content"
          onChange={handleChange}
          value={note.content}
          placeholder="Take a note..."
          rows="3"
        />
        <button className="button" onClick={submitNote}>Add</button>
      </form>
    </div>
  );
}

export default CreateArea;

I would also appreciate if you can provide a review of my code because I am a beginner and that would definitely help me.如果您能提供对我的代码的审查,我也将不胜感激,因为我是初学者,这肯定会对我有所帮助。

Try this approach, (just an assumption)试试这个方法,(只是一个假设)

  function deleteNote(id) {
    setNotes(notes => {
      const filteredNotes =  notes.filter((noteItem) => {
        return noteItem._id !== id;
      });
      return [...filteredNotes];
    });
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 单击按钮时页面会奇怪地刷新 - The page will strangely refresh when I click the button 当我点击提交按钮我的javascript第一个警报框显示在移动设备但在桌面上工作正常 - when I click on submit button my javascript first alert box show in mobile device but works fine in desktop 当我单击按钮将所有其他按钮更改为暗模式时,它只工作一次 - When I click the button to change all the another buttons to dark mode, it works just a single time 当我单击删除按钮时,它只是刷新而不是删除 - When I click delete button it's just refreshing but not deleting 单击浏览器后退按钮时刷新当前页面(chrome) - Refresh the current page when i click the browser back button(chrome) 当我单击一个按钮时,页面不会在 React Javascript 中刷新 - When I click a button the page does not refresh in React Javascript 当我单击项目列表上的复选框并删除它们时,并非所有项目都被删除,但是当我只勾选一个时,它工作正常。 为什么? - When I click checkbox on a list of items and delete them not all of them are removed, but when I only check off one it works fine. Why? 按钮 onClick 事件不起作用,但当我在 Chrome 中显示检查模式时工作正常 - Button onClick event does not work but works just fine when I display the Inspect mode in Chrome 为什么当我点击下一页时,编辑或删除按钮不起作用? - Why when I click on the next page the button edit or delete is not working? 当我点击编辑按钮时出现问题,所有其他元素都听点击,但我只需要我点击的那个 - A problem when i click on edit button, all the other elements listen to the click but i need just the one i click on
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM