使用Mongoose和Redux删除记录

时间:2017-10-03 11:04:42

标签: node.js mongodb reactjs mongoose redux

当用户按下给定记录的按钮时,我想删除mongoDB中的记录。供参考:

enter image description here

我已经设置了所有的mongoose和redux代码,但是我收到了这个错误: enter image description here

这是我的行动:

//deletes a survey when user clicks button
export const deleteSurvey = (surveyId) => async dispatch => {
  const response = await axios.delete("/api/surveys", surveyId);
  dispatch({ type: FETCH_SURVEYS, payload: response.data });
};

这是我的路线处理程序:

app.delete("/api/surveys", requireLogin, (req, res) => {
    Survey.findByIdAndRemove(req.surveyId, (err, survey) => {
      let response = {
        message: "Survey successfully deleted",
      };
      res.status(200).send(response);
    });
  });

正在基于组件的反应组件内呈现记录列表。我正在导入我的动作:

import { deleteSurvey } from "../../actions";

在按钮的onClick事件上触发了对该操作的调用:

<button
    onClick={() => this.props.deleteSurvey(survey._id)}
    className="btn-floating btn-large red"
   >
   <i className="material-icons">clear</i>
</button>

如何解决此错误?

编辑:组件连接

function mapStateToProps({ surveys }) {
  return { surveys }; //returns the surveys reducer from the combined reducers
}

export default connect(mapStateToProps, { fetchSurveys })(SurveyList);

编辑:新错误消息

enter image description here

指的是:

return this.props.surveys.map(survey => {...}

编辑:从API

获取调查
const surveys = await Survey.find({ _user: req.user.id }) //get all surveys for the current user
      .select({ recipients: false }); //dont include recipients
    res.send(surveys);

2 个答案:

答案 0 :(得分:1)

您需要使用React-Redux's connect更高阶函数将操作映射到您的组件。

注意:这不是您应该编写代码的方式,仅用于演示

import React from 'react';
import { connect } from 'react-redux';
import { deleteSurvey } from "../../actions";

const SurveyList = ({ survey, handleDeleteSurvey }) => {
  return <div>
            <button
              onClick={() => handleDeleteSurvey(survey._id)}
              className="btn-floating btn-large red" >
              <i className="material-icons">clear</i>
            </button>
         </div>
}

const mapStateToProps = ({ surveys }) => {
  return { 
    surveys 
  } 
}

const mapDispatchToProps = dispatch => {
  return {
    //note that this code assumes deleteSurvery is a thunk
    handleDeleteSurvey: id => dispatch(deleteSurvey(id))
  }
}


export default connect(mapStateToProps, mapDispatchToProps)(SurveyList);

答案 1 :(得分:1)

您尚未将操作与组件相关联:

export default connect(mapStateToProps, { fetchSurveys, deleteSurvey })(SurveyList);

编辑:您的第二个错误来自于地图仅适用于数组,因此您需要确认surveys是您可以使用的数组:{{1} }