我正在创建一个Reaction+Express应用程序,允许用户制作他们想要做的网络项目列表.它们显示在网页上的表格中,表格下方有一个表单,允许用户向Web项目添加新条目,并弹出警告,说明已添加新条目.我已经能够创建表单和表格,但是每次我按下Add按钮时,alert 就会出现,所以我知道我的函数起作用了,但它一直在添加一个空对象,而不是用户在表单中输入的信息

server.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 5000;
const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

let webProjects = [

  {
    ID: 1,
    TITLE: "React Game",
    DESCRIPTION: "Tic tac toe game created using Create React App",
    URL: "http://someURL/myapp/game/",
  },
  {
    ID: 2,
    TITLE: "Online Store",
    DESCRIPTION: "Online store created with HTML, CSS and Javascript.",
    URL: "http://someURL2/shop/index",
  },
  {
    ID: 3,
    TITLE: "Online Store",
    DESCRIPTION: "Online store created with HTML, CSS and Angular.",
    URL: "http://someURL3/shop2/index",
  }
] 

app.get("/api", (req, res) => {

    res.json({ webProjects });
})



app.post("/api/create", (req, res) => {

  response ={
    ID:req.body.id,
    TITLE:req.body.title,
    DESCRIPTION:req.body.description,
    URL:req.body.url,
  };


  res.json(response);
  webProjects.push(response);



})

app.listen(PORT, () => {
   console.log("Server started on port 5000")
})

FormData.js
import React, { useState } from 'react'

function FormData() {
    const [content, setContent] = useState({ webProjects: []})
    const [ID, setID] = useState("");
    const [TITLE, setTITLE] = useState("");
    const [DESCRIPTION, setDESCRIPTION] = useState("");
    const [URL, setURL] = useState("");

    const create = (e) => {
        fetch("/api/create", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                TITLE,
                DESCRIPTION,
                URL,
            }),
        })
        .then((response) => response.json())
        .then((response) => {
            alert("A new item has been added")
            setContent(response.copyContent)
        })
    }
  return (
    <div>
        <form>
            <label>
                ID:
                <input
                    name="id"
                id="id"
                type="text"
                value={ID}
                onChange={(e) => setID(e.target.value)}
                required
                />
            </label>
            <label>
                Title:
                <input
                    name="title"
                    id="title"
                    type="text"
                    value={TITLE}
                    onChange={(e) => setTITLE(e.target.value)}
                    required
                />
            </label>
            <label>
                Description:
                <input
                    name="description"
                    id="description"
                    type="text"
                    value={DESCRIPTION}
                    onChange={(e) => setDESCRIPTION(e.target.value)}
                    required
                />
            </label>
            <label>
                URL:
                <input
                    name="url"
                    id="url"
                    type="text"
                    value={URL}
                    onChange={(e) => setURL(e.target.value)}
                    required
                />
            </label>
            <button className='add-btn' type="button" onClick={(e) => create(e)}>Add</button>
        </form>
    </div>
  )
}

export default FormData

App.js

import React, { useEffect, useState } from 'react'
import { TableData } from './components/TableData'
import FormData from './components/FormData'



function App() {

  const [content, setContent] = useState({ webProjects: []})

  useEffect(() => {
    fetch("/api", {
      method: "GET",
      headers: {
        "Content-type": "application/json",
      }
    }).then((response) => response.json()
    ).then((response) => {setContent(response)}
    )
  }, [])

  return (
    <div>
      <TableData projectData={content.webProjects}/>
      <FormData />
    </div>
  )
}

export default App

推荐答案

看起来您没有在FormData组件中正确处理状态更新.您正在更新Create函数中的内容状态,而没有更新其中的WebProjectsarray.

.then((response) => {
    alert("A new item has been added")
    setContent((prevContent) => ({
        webProjects: [...prevContent.webProjects, response]
    })
    // And perhaps you want to reset some other states too?
    setID("")
    setTITLE("")
    setDESCRIPTION("")
    setURL("")
)

Node.js相关问答推荐

使用OpenAI API时遇到问题

如何从puppeteer的page. evaluate()中获取流数据?(node.js)

如何在Node js中从MongoDB获取特定数据,使用GET方法?

Jest由于UUID而无法解析测试,即使在Jest中启用ESModule支持后也是如此

Firebase-admin筛选器.或只考虑第一个WHERE子句

Node.js PNG缓冲区获取未知图像格式错误

PM2 是否需要成为其托管项目的依赖项?

有没有办法判断 UUID 是否是使用 node.js 中的特定命名空间生成的?

我如何在 Raku 的供应中注册不同的事件?

在 .htaccess 中从非 www 切换到 www 后如何解决无法访问该站点?

为什么我的 npm 脚本中的 glob 不起作用?

使用mongoose 创建新文档并仅取回选定的字段

nuxt:在 docker 镜像中找不到

响应发送 200 而不是 403

如何在 NodeJs 中下载和解压缩内存中的 zip 文件?

如何在 node 中转义 shell 命令的字符串?

Puppeteer 记录在 page.evaluate

如何解决 Socket.io 404(未找到)错误?

Fluxible 中的脱水和再水合代表什么?

Node.js - 判断是否安装了模块而不实际需要它