为什么在使用MERN应用程序时无法立即更新屏幕?

如何解决为什么在使用MERN应用程序时无法立即更新屏幕?

我不太确定如何把我的问题说出来,所以首先我解释了我的工作。 我正在构建一个项目,我的项目流程如下:


  1. 第一个屏幕:
    a)用户输入他的名字,然后向后端服务器发出发布请求。
    b)在后端,我掌握了该名称并将其分配给变量“用户名”,然后 我在MongoDB数据库中搜索该“用户名”,如果不存在 我通过名称创建一个文档:“用户名”,然后将其重定向到route(“ / notes”),或者如果他已经存在,则将其重定向到route(“ / notes”)。我的集合的架构如下:
    const noteSchema = new mongoose.Schema({ 名称:字符串, 注意:[ { noteTitle:字符串, noteContent:字符串, }, ], });
    c)当我向后端服务器发出“发布”请求时,用于解释点“ a”(如上所述)的代码如下所示
import React,{ useState } from "react";
import Axios from "axios";

function EnterNameTemplate(props) {
  const [nameMe,setNameMe] = useState("");

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

  function handleClick(event) {
    const nameObject = {
      name: nameMe,};
    Axios.post("/getName",nameObject)
      .then(() => {
        console.log("Inside axios.post in EnterName template");
        setNameMe("");
        props.getName();
      })
      .catch(() => {
        console.log("Error in axios.post in EnterName template");
      });
    event.preventDefault();
  }
  return (
    <form className="EnterNameTemplate">
      <label>Enter Your Name below</label>
      <input
        type="text"
        name="name"
        placeholder="Enter your name here"
        onChange={handleChange}
      />
      <button type="submit" onClick={handleClick}>
        Submit
      </button>
    </form>
  );
}

export default EnterNameTemplate;

d)下面显示了解释如何在后端处理该发布请求的代码

router.post("/getName",(req,res) => {
  userName = req.body.name;
  console.log(userName);
  Note.findOne({ name: userName },(err,foundUser) => {
    if (!foundUser) {
      const newUser = new Note({
        name: userName,notes: [
          {
            noteTitle: "This is your first note",noteContent: "This is your notes description part",},],});
      newUser.save();
      res.redirect("/notes");
    } else {
      res.redirect("/notes");
      console.log("name found and exists already !");
    }
  });
});

  1. 第二个屏幕:a)在第一个屏幕上,当用户输入自己的名字时,我使用React Hooks更新了屏幕,第1点c)代码中显示的props.getName()函数使此功能正常工作。
    b)我的App.jsx中的代码如下:
import React,{ useState,useEffect } from "react";
import Header from "./Header";
import CreateArea from "./CreateArea";
import Footer from "./Footer";
import Note from "./Note";
import EnterNameTemplate from "./EnterNameTemplate";
import axios from "axios";

function App() {
  const [finalNoteDB,setFinalNoteDB] = useState([]);
  const [isName,setName] = useState(false);
  function getNote() {
    axios
      .get("/notes")
      .then((response) => {
        // respond.data.notes this contains the notes array
        setFinalNoteDB(response.data.notes);
      })
      .catch((err) => {
        if (err) {
          console.log("error in app.jsx");
        }
      });
  }
  function getName() {
    setName(true);
  }
  useEffect(() => {
    let ignore = false;

    if (!ignore) getNote();
    return () => {
      ignore = true;
    };
  },[]);
  return (
    <React.Fragment>
      {isName ? (
        <div>
          <Header />
          <CreateArea getNote={getNote} />
          {finalNoteDB.map((singleNote,index) => {
            return (
              <Note
                key={index}
                id={singleNote._id}
                title={singleNote.noteTitle}
                content={singleNote.noteContent}
                getNote={getNote}
              />
            );
          })}

          <Footer />
        </div>
      ) : (
        <EnterNameTemplate getNote={getNote} getName={getName} />
      )}
    </React.Fragment>
  );
}

export default App;

c)其余的自定义标签如下:

import React,{ useState } from "react";
import AddIcon from "@material-ui/icons/Add";
import { Fab,Zoom } from "@material-ui/core";
import Axios from "axios";

function CreateArea(props) {
  const [note,setNote] = useState({
    noteTitle: "",noteContent: "",});
  const [zoom,setZoom] = useState(false);

  function handleChange(event) {
    const { name,value } = event.target;
    setNote((prevNote) => {
      return {
        ...prevNote,[name]: value,};
    });
  }
  function handleClick(event) {
    event.preventDefault();
    Axios({
      url: "/save",method: "POST",data: note,})
      .then(() => {
        console.log("Data sent successfully to mongoose");
      })
      .catch(() => {
        console.log("Error detected !");
      });
    setNote({
      noteTitle: "",});
    props.getNote();
  }
  function setZoomFunction() {
    setZoom(true);
  }

  return (
    <div>
      <form className="create-note">
        {zoom ? (
          <input
            name="noteTitle"
            placeholder="Title"
            onChange={handleChange}
            value={note.noteTitle}
          />
        ) : null}

        <textarea
          name="noteContent"
          placeholder="Take a note..."
          rows={zoom ? "3" : "1"}
          onChange={handleChange}
          value={note.noteContent}
          onClick={setZoomFunction}
        />
        <Zoom in={zoom}>
          <Fab onClick={handleClick}>
            <AddIcon />
          </Fab>
        </Zoom>
      </form>
    </div>
  );
}

export default CreateArea;

d)

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

function Note(props) {
  function deleteNoteInNote() {
    const objectID = {
      id: props.id,};
    Axios.post("/delete",objectID);
    props.getNote();
  }
  return (
    <div className="note">
      <h1>{props.title}</h1>
      <p>{props.content}</p>
      <button onClick={deleteNoteInNote}>
        {" "}
        <DeleteIcon />{" "}
      </button>
    </div>
  );
}

export default Note;

  1. 所有文件中的代码如下:
    一种。 server.js (用于处理后端)
const express = require("express");
const router = express.Router();
const Note = require("../models/Notes");
var userName = "";

router.get("/notes",function (req,res) {
  Note.findOne({ name: userName },data) => {
    if (!err) {
      res.send(data);
    } else {
      console.log("Error in get('/notes')");
    }
  });
});

router.post("/save",res) {
  const data = req.body;
  Note.findOne({ name: userName },foundUser) => {
    if (!err) {
      foundUser.notes.push(data);
      foundUser.save();
    }
  });
  res.json({
    msg: "success",});
});

router.post("/delete",res) {
  Note.findOneAndUpdate(
    { name: userName },{ $pull: { notes: { _id: req.body.id } } },foundUser) => {
      if (!err) {
        console.log("Succes in deleting");
        // res.redirect("/notes");
      } else {
        console.log(err);
      }
    }
  );
});

router.post("/getName",});
      newUser.save();
      res.redirect("/notes");
    } else {
      res.redirect("/notes");
      console.log("name found and exists already !");
    }
  });
});
module.exports = router;

b) App.jsx 中的代码在点2)b)中给出。
c) Notes.jsx,CreateArea.jsx 的代码分别在2)d),2)c)中显示。
d) EnterNameTemplate.jsx 的代码如下所示:

import React,nameObject)
      .then(() => {
        console.log("Inside axios.post in EnterName template");
        setNameMe("");
        props.getName();
      })
      .catch(() => {
        console.log("Error in axios.post in EnterName template");
      });
    event.preventDefault();
  }
  return (
    <form className="EnterNameTemplate">
      <label>Enter Your Name below</label>
      <input
        type="text"
        name="name"
        placeholder="Enter your name here"
        onChange={handleChange}
      />
      <button type="submit" onClick={handleClick}>
        Submit
      </button>
    </form>
  );
}

export default EnterNameTemplate;

e)显示我的目录结构的图片是: https://www.flickr.com/photos/189671520@N03/50214532896/in/dateposted/

  1. a)问题是当我输入名称ex:“ test01”时,然后我成功获得了第二个屏幕,即“添加注释”屏幕,但是请问是否使用
    noteTitle:“第一天”
    noteContent:“洗个澡”
    。 b)成功添加注释后,当我刷新页面并假设这次输入名称“ test02”时。然后,而不是显示新的空白便笺,而是显示包含名为“ test01”的人的便笺(即上一个用户的便笺)。
    c)然后,当我添加新便笺时,说
    noteTitle :“第2天”
    noteContent:“小睡”
    。然后,我立即获得当前用户的文档(即,名为name =“ test02”的notes数组)。
    d)同样,如果我刷新页面,然后使用name =“ test03”,则首先得到包含前人注释的显示(在这种情况下为“ test02”),并且如果我添加新注释或说刷新页面并登录再次使用名称“ test02”,然后才获得当前用户的notes数组(在这种情况下为“ test03”)


  1. 那么如何克服呢?我到底有什么错误,还是由于猫鼬反应问题引起的?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-