【发布时间】:2020-08-16 16:48:32
【问题描述】:
我需要从我的 mongodb 数据库“cmets”集合中更新我的“comment”对象。更具体地说,当我按下“Like”按钮时,我想使用 axios 发送一个 put 请求,我可以在“comment”对象中将 +1 添加到“likes”。
所有其他操作都工作正常(获取 cmets、添加它们等),我唯一苦苦挣扎的是更新评论喜欢。
如果有人能提供帮助,我将不胜感激。提前致谢!
在这里我添加了我的代码:
//--------CommentComponent.js
import React, { useState, useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { getComments, updateComment } from '../actions/commentActions'
const PostPage = ({ match }) => {
const commentz = useSelector(store => store.comment.comments)
const dispatch = useDispatch()
useEffect(() => {
dispatch(getComments())
}, [dispatch])
const handleLike = e => {
dispatch(updateComment(e.target.id))
}
return (
{commentz ? commentz.map(comm =>
comm.forWich === match.params.id ?
<div key={comm._id} className={styles.comment}>
<div>
<h2>{comm.name}</h2>
</div>
<div>
<p>{comm.comment}</p>
</div>
{comm.likes} <button id={comm} onClick={handleLike}>Like</button>
<div>
</div>
: null
) : null}
)
}
export default PostPage
//-------Comment.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const CommentSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
comment: {
type: String,
required: true
},
forWich: {
type: String,
required: true
},
likes: {
type: Number,
default: 0
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Comment = mongoose.model('comment', CommentSchema);
//-------cmets.js
const express = require('express');
const router = express.Router();
// Comments Model
const Comment = require('../../models/Comment');
// @route UPDATE api/comments
// @desc Update comment
// @access Public
router.put('/:id', (req, res, next) => {
Comment.findbyId(req.params.id)
.then(comment => comment.update(req.body))
.catch(next);
})
module.exports = router;
//--------CommentActions.js
import axios from 'axios';
import {
GET_COMMENTS,
ADD_COMMENTS,
COMMENTS_LOADING,
GO_COMMENTS,
UPDATE_COMMENTS
} from './types';
export const updateComment = comment => {
return function(dispatch) {
axios
.put(`/api/comments`, comment)
.then(res =>
dispatch({
type: UPDATE_COMMENTS,
payload: comment
})
)
}
}
//--------CommentReducer.js
import {
GET_COMMENTS,
ADD_COMMENTS,
COMMENTS_LOADING,
GO_COMMENTS,
UPDATE_COMMENTS
} from '../actions/types';
const initialState = {
comments: []
}
export default function(state = initialState, action) {
switch(action.type) {
case UPDATE_COMMENTS:
return {
...state,
comments: state.comments.map(comm => comm._id === action.payload._id ? comm.likes = action.payload + 1 : comm.likes)
}
}
}
【问题讨论】:
标签: node.js reactjs mongodb express mern