首页 > 解决方案 > 如何在 React 中成功提交后清除输入字段,使用 useEffect 功能组件

问题描述

我正在开发一个 Mern-stack 应用程序,但在成功发布请求后我无法清除输入字段。我正在使用带有 useEffect 的基于函数的组件。

我尝试了我在 Stack Overflow 上获得的示例,但它仍然不起作用。提交成功后,输入仍然留在输入字段中。我该如何澄清?

提交后我试过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>
 );
 }
}

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

标签: node.jsreactjs

解决方案


在您的onSubmit函数中,调用setName("")setEventComment("")清除这些值。

另外,为了遵循约定,我将重命名setEventComment为,setEventDescription因为状态变量被命名为eventDescriptionnot eventComment


推荐阅读