我正在按照教程尝试学习 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)}
>
×
</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);
在我的 reducer 中:
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 返回语句中使用 { 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)
};
希望这会有所帮助!
关于javascript - 使用 Redux 未从数组中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60894419/