Node.js 如何使用useEffect功能组件在React中成功提交后清除输入字段

Node.js 如何使用useEffect功能组件在React中成功提交后清除输入字段,node.js,reactjs,Node.js,Reactjs,我正在处理一个Mern堆栈应用程序,但是在成功的post请求之后,我无法清除输入字段。我使用的是一个基于函数的组件,具有useEffect 我尝试了我在这里得到的关于堆栈溢出的例子,但仍然不起作用。成功提交后,输入仍保留在输入字段中。我怎样才能弄清楚 我在提交后尝试了setCommentData([]),但没有成功 这是我的组件 export default function EventAndComments(props) { const EventComment = (props) =

我正在处理一个Mern堆栈应用程序,但是在成功的post请求之后,我无法清除输入字段。我使用的是一个基于函数的组件,具有useEffect

我尝试了我在这里得到的关于堆栈溢出的例子,但仍然不起作用。成功提交后,输入仍保留在输入字段中。我怎样才能弄清楚

我在提交后尝试了
setCommentData([])
,但没有成功

这是我的组件

export default function EventAndComments(props) {
    const EventComment = (props) => (
     <CardContent>
       <Typography variant="body2" color="textSecondary" component="p">
         {props.comment.name}
       </Typography>
       <Typography variant="body2" color="textSecondary" component="p">
        {props.comment.description}
       </Typography>
    </CardContent>
  );

  const theme = useTheme();
  const [events, setEventData] = useState([]);
  const [comments, setCommentData] = useState([]);

  const useStyles = makeStyles((theme) => ({
    root: {
      maxWidth: 550,
    },
    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) => {
       setEventData(response.data);
    })

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

  .then((response) => {
    setCommentData(response.data.eventcomments);
  })
  .catch(function (error) {
    console.log(error);
  });
};
useEffect(() => {
 onPageLoad();
}, []);


 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 [eventDescription, setEventComment] = React.useState("");
const [name, setName] = React.useState("");

const handleChange = (parameter) => (event) => {
  if (parameter === "name") {
    setName(event.target.value);
  }
  if (parameter === "description") {
    setEventComment(event.target.value);
  }
};

const onSubmit = useCallback(
(e) => {
  e.preventDefault();

  axios
    .post(
      "http://localhost:9000/events/" +
        props.match.params.id +
        "/eventcomment",
      { name: name, description: eventDescription }
    )

    .then(function (response) {
      onPageLoad();
    })

    .catch(function (error) {
      console.log(error);
    });
  },
  [props.match.params.id, name, eventDescription]
 );

 let eventCommentList = comments.map((comment, k) => (
   <EventComment comment={comment} key={k} />
 ));

 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}
    >
      {events.title}
    </h3>
    <CardHeader
      avatar={
        <Avatar aria-label="recipe" className={classes.avatar}>
          CB
        </Avatar>
      }
      action={
        <IconButton aria-label="settings">
          <MoreVertIcon />
        </IconButton>
      }
      title={getTitle(
        Date.parse(events.startingDate),
        Date.parse(events.closingDate)
      )}
      subheader={getEnded(
        Date.parse(events.startingDate),
        Date.parse(events.closingDate)
      )}
      style={{ background: "#DCDCDC" }}
    />
    <CardMedia
      className={classes.media}
      image={events.eventImage}
      title="Paella dish"
    />
    <CardContent>
      <Typography variant="body2" color="textSecondary" component="p">
        {events.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={name}
        onChange={handleChange("name")}
        label="Name"
      />
    </FormControl>

    <FormControl variant="outlined">
      <InputLabel htmlFor="component-outlined">Description</InputLabel>
      <OutlinedInput
        id="component-outlined"
        value={eventDescription}
        onChange={handleChange("description")}
        label="Description"
      />
    </FormControl>
    <Button type="submit" fullWidth variant="contained" color="primary">
      Create Comment
    </Button>
  </form>
  <CardContent>{eventCommentList}</CardContent>
  </Grid>
 );
 }
}
导出默认函数EventAndComments(props){
const EventComment=(道具)=>(
{props.comment.name}
{props.comment.description}
);
const theme=useTheme();
const[events,setEventData]=useState([]);
const[comments,setCommentData]=useState([]);
const useStyles=makeStyles((主题)=>({
根目录:{
最大宽度:550,
},
媒体:{
高度:0,,
paddingTop:“86%,//16:9
显示:“flex”,
flexDirection:“列”,
对齐项目:“中心”,
},
扩展:{
变换:“旋转(0度)”,
marginLeft:“自动”,
转换:theme.transitions.create(“转换”{
持续时间:theme.transitions.duration.shortest,
}),
},
expandOpen:{
变换:“旋转(180度)”,
},
化身:{
背景颜色:红色[500],
},
}));
const classes=useStyles();
const[expanded,setExpanded]=React.useState(false);
常量handleExpandClick=()=>{
setExpanded(!expanded);
};
useffect(()=>{
axios
.得到(
"http://localhost:9000/events/" +
props.match.params.id+
“/eventcomments”
)
。然后((响应)=>{
setEventData(response.data);
})
.catch(函数(错误){
console.log(错误);
});
}, []);
const onPageLoad=()=>{
axios
.得到(
"http://localhost:9000/events/" +
props.match.params.id+
“/eventcomments”
)
。然后((响应)=>{
setCommentData(response.data.eventcomments);
})
.catch(函数(错误){
console.log(错误);
});
};
useffect(()=>{
onPageLoad();
}, []);
const nowIso=新日期();
常量getTitle=(开始日期、结束日期)=>{
const now=Date.parse(nowIso);
如果(现在结束日期){
返回“实时:”+“+时刻(开始日期)。格式(“LLLL”);
}
返回“开始:”+“+时刻(开始日期)。格式(“LLLL”);
};
const getend=(开始日期、结束日期)=>{
const now=Date.parse(nowIso);
如果(现在结束日期){
return“Will End:”+“+时刻(startDateTs).format(“LLLL”);
}
返回“结束:”+“+时刻(开始日期)。格式(“LLLL”);
};
const[eventDescription,setEventComment]=React.useState(“”);
const[name,setName]=React.useState(“”);
常量handleChange=(参数)=>(事件)=>{
如果(参数==“名称”){
setName(event.target.value);
}
如果(参数==“说明”){
setEventComment(event.target.value);
}
};
const onSubmit=useCallback(
(e) =>{
e、 预防默认值();
axios
.邮政(
"http://localhost:9000/events/" +
props.match.params.id+
“/eventcomment”,
{name:name,description:eventDescription}
)
.然后(功能(响应){
onPageLoad();
})
.catch(函数(错误){
console.log(错误);
});
},
[props.match.params.id、名称、事件描述]
);
让eventCommentList=comments.map((comment,k)=>(
));
返回(
{events.title}
{events.description}
名称
描述
创建注释
{eventCommentList}
);
}
}

我已经在上面添加了所有代码。

在您的
onSubmit
函数中,调用
setName(“”)和
setEventComment(“”)来清除这些值


另外,为了遵循惯例,我会将
setEventComment
重命名为
setEventDescription
,因为state变量名为
eventDescription
而不是
eventComment

,我看不到您在提交后在哪里更新表单中使用的状态值?非常感谢,我真的很努力。对于非传统的命名,我将重命名为现在,我本来打算这样做,但忘记了。再次感谢你@齐克