没有使用Redux从数组中删除项目

时间:2020-03-27 21:35:13

标签: javascript reactjs redux react-redux

我正在按照一个教程尝试学习Redux。我执行了第一个操作,这是一个简单的GET API调用,但是卡在了我要创建的下一个操作上。该代码如下所示:

在组件中:

class ShoppingList extends Component {
  componentDidMount() {
    this.props.getItems();
  }

  handleClick = id => {
    console.log("component " + id);
    this.props.deleteItem(id);
  };

  render() {
    const { items } = this.props.item;

    return (
      <Container>
        <ListGroup>
          <TransitionGroup className="shoppingList">
            {items.map(({ id, name }) => (
              <CSSTransition key={id} timeout={500} classNames="fade">
                <ListGroupItem>
                  <Button
                    className="button1"
                    color="danger"
                    size="sm"
                    onClick={e => this.handleClick(id, e)}
                  >
                    &times;
                  </Button>
                  {name}
                </ListGroupItem>
              </CSSTransition>
            ))}
          </TransitionGroup>
        </ListGroup>
      </Container>
    );
  }
}

ShoppingList.propTypes = {
  getItems: PropTypes.func.isRequired,
  item: PropTypes.object.isRequired,
  deleteItem: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  item: state.item
});

export default connect(mapStateToProps, { getItems, deleteItem })(ShoppingList);

在我的减速器中:

const initialState = {
  items: [
    { id: 3, name: "Eggs" },
    { id: 4, name: "Milk" },
    { id: 5, name: "Steak" },
    { id: 6, name: "Water" }
  ]
};

export default function(state = initialState, action) {
  switch (action.type) {
    case GET_ITEMS:
      return {
        ...state
      };
    case DELETE_ITEM:
      console.log("reducer");
      return {
        ...state,
        items: state.items.filter(item => item.id !== action.id)
      };
    default:
      return state;
  }
}

在我的操作文件中:

export const getItems = () => {
  return {
    type: GET_ITEMS
  };
};

export const deleteItem = id => {
  console.log("actions");
  return {
    type: DELETE_ITEM,
    payload: id
  };
};

但是,当我单击按钮尝试从列表中删除项目时,什么也没有发生。我可以在Redux控制台中看到正在分派操作,但是它似乎没有任何作用。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您正在进行deleteItem操作{ type, payload }。相反,您可以在化简的return语句中使用{ type, id }或使用payload

我将执行以下操作-因此您将id而不是action传递给payload

export const deleteItem = id => {
  console.log("actions");
  return {
    type: DELETE_ITEM,
    id
  };
};

或者是以后使用的最佳选择-保持payload仅将id添加为属性:

// action
export const deleteItem = id => {
  console.log("actions");
  return {
    type: DELETE_ITEM,
    payload: { id }
  };
};

// reducer
case DELETE_ITEM:
   // here destructuring the property from payload
   const { id } = action.payload;
   return {
      ...state,
      items: state.items.filter(item => item.id !== id)
   };

我希望这会有所帮助!