首页 > 解决方案 > 如何在 Express 或 React 中对评论进行排序以在顶部显示最新评论,在底部显示旧评论

问题描述

我正在开发一个 Mern-stack 应用程序,在我的应用程序中,我有一个事件模型,并且该事件有很多评论。如何对评论进行排序以在顶部显示最新评论而旧评论在底部?

我应该在哪里做这个逻辑?在 API(后端)还是前端(React)?评论有一个名为createdAt新日期的属性,在创建评论时会插入 createdAt 属性。

这就是我在我的 Express 后端获取带有评论的事件的方式

router.get("/:id/eventcomments", async (req, res) => {
  const event = await Event.findById({ _id: req.params.id }).populate(
    "eventcomments"
  );
  res.json(event);
});

这是用于评论的模式模型。

const eventcommentSchema = new mongoose.Schema({

description: {
    type: String,
    required: true
},
name: {
    type: String,
    required: true
},
createdAt: { 
    type: Date, 
    required: true, 
    default: Date.now
},
  event: { type: Schema.Types.ObjectId, ref: 'Event'}
})

这是我的组件

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.jsreactjsexpress

解决方案


我已经设法使它与这段代码一起工作。

router.get("/:id/eventcomments", async (req, res) => {
  Event.findById({ _id: req.params.id })
  .populate("eventcomments", "_id name description createdAt", 
    null, {
    sort: { createdAt: -1 },
  })
 .exec(function (error, results) {
   res.json(results);
 });
});

我在这里所拥有的与上面给出的示例之间的区别在于它要求我传入我的字段名称。


推荐阅读