如何使用useState在React中发布API

如何解决如何使用useState在React中发布API

我正在使用Material-UI开发Mern-stack应用程序。我有一个事件模型,一个事件有很多评论。我现在面临的挑战是如何用functional-based component在EVent上发表评论。我以前曾使用基于类的组件进行此工作,但现在我决定将代码更改为使用基于函数的组件,但我不知道该如何实现。我在控制台中遇到的错误是404 not found。如何设置useState以通过Axios正确发送写入数据?

import React,{ useState,useEffect } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
import AddComingWithModal from "../components/coming-with- 
modal.component";
import { makeStyles } from "@material-ui/core/styles";
import clsx from "clsx";
import Card from "@material-ui/core/Card";
import CardHeader from "@material-ui/core/CardHeader";
import CardMedia from "@material-ui/core/CardMedia";
import CardContent from "@material-ui/core/CardContent";
import CardActions from "@material-ui/core/CardActions";
import Collapse from "@material-ui/core/Collapse";
import Avatar from "@material-ui/core/Avatar";
import IconButton from "@material-ui/core/IconButton";
import Typography from "@material-ui/core/Typography";
import { red } from "@material-ui/core/colors";
import FavoriteIcon from "@material-ui/icons/Favorite";
import ShareIcon from "@material-ui/icons/Share";
import ExpandMoreIcon from "@material-ui/icons/ExpandMore";
import MoreVertIcon from "@material-ui/icons/MoreVert";
import { useTheme } from "@material-ui/core/styles";
import useMediaQuery from "@material-ui/core/useMediaQuery";
import Grid from "@material-ui/core/Grid";
import moment from "moment";

import FilledInput from "@material-ui/core/FilledInput";
import FormControl from "@material-ui/core/FormControl";
import FormHelperText from "@material-ui/core/FormHelperText";
import Input from "@material-ui/core/Input";
import InputLabel from "@material-ui/core/InputLabel";
import OutlinedInput from "@material-ui/core/OutlinedInput";

export default function EventAndComments(props) {
 const url = props.location.pathname;
 const theme = useTheme();
 const [eventComments,setTileData] = useState([]);

 const useStyles = makeStyles((theme) => ({
   root: {
    maxWidth: 850,},media: {
   height: 0,paddingTop: "86%",// 16:9
  display: "flex",flexDirection: "column",alignItems: "center",expand: {
  transform: "rotate(0deg)",marginLeft: "auto",transition: theme.transitions.create("transform",{
    duration: theme.transitions.duration.shortest,}),expandOpen: {
  transform: "rotate(180deg)",avatar: {
  backgroundColor: red[500],}));

const classes = useStyles();
const [expanded,setExpanded] = React.useState(false);

const handleExpandClick = () => {
 setExpanded(!expanded);
};

useEffect(() => {
  axios
   .get(
     "http://localhost:9000/events/" +
       props.match.params.id +
       "/eventcomments"
   )
  .then((response) => {
    setTileData(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });
},[]);

const nowIso = new Date();
const getTitle = (startDateTs,endDateTs) => {
 const now = Date.parse(nowIso);

 if (endDateTs <= now) {
  return "Started:" + " " + moment(startDateTs).format("LLLL");
}

if (startDateTs < now && endDateTs > now) {
  return "Live:" + " " + moment(startDateTs).format("LLLL");
}

 return "Starting:" + " " + moment(startDateTs).format("LLLL");
};

const getEnded = (startDateTs,endDateTs) => {
  const now = Date.parse(nowIso);

 if (endDateTs <= now) {
   return "Ended:" + " " + moment(startDateTs).format("LLLL");
 }

if (startDateTs < now && endDateTs > now) {
  return "Will End:" + " " + moment(startDateTs).format("LLLL");
 }

  return "Ends:" + " " + moment(startDateTs).format("LLLL");
};

const [setEventComment,setName] = React.useState("");

const handleChange = (event) => {
 setName({ ...setEventComment,[event.target.name]: event.target.value 
 });
};

const onSubmit = (e) => {
  e.preventDefault();
  axios
    .post(
      "http://localhost:9000/events/" + props.match.params.id,setEventComment
    )
    .then(function (response) {
     console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
 };

return (
<Grid
  container
  spacing={0}
  direction="column"
  alignItems="center"
  justify="center"
  style={{ minHeight: "100vh" }}
>
  <Card className={classes.root}>
    <h3
      style={{
        background: "   #800000",color: "white",textAlign: "center",}}
      className={classes.cardheader}
    >
      {eventComments.title}
    </h3>
    <CardHeader
      avatar={
        <Avatar aria-label="recipe" className={classes.avatar}>
          CB
        </Avatar>
      }
      action={
        <IconButton aria-label="settings">
          <MoreVertIcon />
        </IconButton>
      }
      title={getTitle(
        Date.parse(eventComments.startingDate),Date.parse(eventComments.closingDate)
      )}
      subheader={getEnded(
        Date.parse(eventComments.startingDate),Date.parse(eventComments.closingDate)
      )}
      style={{ background: "#DCDCDC" }}
    />
    <CardMedia
      className={classes.media}
      image={eventComments.eventImage}
      title="Paella dish"
    />
    <CardContent>
      <Typography variant="body2" color="textSecondary" component="p">
        {eventComments.description}
      </Typography>
    </CardContent>
  </Card>
  <form
    className={classes.root}
    noValidate
    autoComplete="off"
    onSubmit={onSubmit}
  >
    <FormControl>
      <InputLabel htmlFor="component-simple">Name</InputLabel>
      <Input
        id="component-simple"
        value={setEventComment.name}
        onChange={handleChange}
      />
    </FormControl>

    <FormControl variant="outlined">
      <InputLabel htmlFor="component-outlined">Name</InputLabel>
      <OutlinedInput
        id="component-outlined"
        value={setEventComment.description}
        onChange={handleChange}
        label="Name"
      />
    </FormControl>
    <input
      type="submit"
      className="btn btn-outline-warning btn-block mt-4"
    />
  </form>
</Grid>

); }

解决方法

问题不是来自useState,而是致电

axios.post(
  "http://localhost:9000/events/" + props.match.params.id,setEventComment
)

您收到的错误是网址

“ http:// localhost:9000 / events /” + props.match.params.id

不存在。我不知道您应该如何发送ID

“ http:// localhost:9000 / events?id =” + props.match.params.id

或其他东西,但这就是您的日志所要解决的问题:

在浏览器控制台中

。 xhr.js:178 POST http:// localhost:9000 / events / 5f35e9c686c3a9132b5067b9 404(未找到)错误:请求失败,状态码为404

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 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-