未使用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控制台中看到该操作正在调度,但它似乎没有任何效果。有什么建议吗?

您在deleteItem中有{ type, payload }操作。相反,您可以在reducer return语句中使用{ type, id }payload

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

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)
};

我希望这能有所帮助!

最新更新