MERN:如何使用_id从猫鼬获取项目以使用删除它

时间:2018-07-05 15:12:57

标签: mongodb reactjs express mongoose redux

我有react / redux 组件

import React, { Component } from 'react';
import { connect } from "react-redux";
import _ from 'lodash';
import {
  onDeleteItem,
  onChangeItemState
} from '../actions/actions.js'

import {
  Button
} from 'reactstrap';

const mapStateToProps = state => ({
  trStore: state
});

class Contenttr extends Component {
  deleteItem() {
    this.props.onDeleteItem(this.props.id);
  }
  changeItem() {
    this.props.onChangeItemState(this.props.id);
  }
  render() {
    return  (
      <tr>
        <td className="text-center"><img src="http://via.placeholder.com/100x50" alt="Logo" /></td>
        <td className="text-center">{this.props.keywords}</td>
        <td className="text-center">{this.props.place}</td>
        <td className="text-center"><Button color="danger" size="sm" onClick={this.deleteItem.bind(this)}>Delete</Button></td>
        <td className="text-center"><Button color="primary" size="sm" onClick={this.changeItem.bind(this)}>Change</Button></td>
      </tr>
    );
  }
}

export default connect(mapStateToProps, { onDeleteItem, onChangeItemState })(Contenttr);

我制作了 API ,以从mongodb(猫鼬)中删除项目:

router.route('/items/:item_id')
    // delete the item with this id (accessed at DELETE http://localhost:3001/api/item/:item_id)
    .delete(function(req, res) {
        Item.remove({
            _id: req.params.item_id
        }, function(err, item) {
            if (err)
                res.send(err);

            res.json({ message: 'Successfully deleted' });
        });
    });

在我的减速器中,我通过这种方式将其从状态中删除:

else if (action.type === "DELETE_ITEM") {
    const delId = action.id;
    const filtered = _.filter(state.filtered,(o) => 
      o.id !== delId
    );
    const itemsList = _.filter(state.filtered,(o) => 
      o.id !== delId
    );
    // console.log('DELETE_ITEM', filtered, "delId", delId);
    return {
      ...state,
      filtered,
      itemsList
    }

我的操作文件如下所示:

export function onDeleteItem(id) {
  return (dispatch) => {
    axios.delete(`http://localhost:3001/api/items/:${id}`)
      .then(res => {
        dispatch({type:"DELETE_ITEM", id: id});
      })
  }
}

我面临的问题是,要使用操作删除项目,我需要使用onDeleteItem函数将_id从组件传递到操作。但是基本的this.props._id向我显示了undefined。如何获取此_id或正确重写API?

0 个答案:

没有答案
相关问题