更改 redux 状态时删除元素
Remove Element when change redux state
我在从 redux 状态删除元素时更新组件时遇到问题。
我的组件:
const mapStateToProps = state => ({
products: state.shoppingBasket.list,
});
const ShoppingBasket = React.createClass({
propTypes: {
removeProduct: React.PropTypes.func.isRequired,
products: React.PropTypes.array,
open: React.PropTypes.func.isRequired,
},
removeFromBasket(index, name) {
this.props.removeProduct(index);
},
render() {
return (
<div>
{this.props.products.map((product, index) => (
<div key={index}>
product.name
<button onClick={() => this.RemoveFromBasket(index)}
</div>
);
)}
</div>
);
},
});
export default connect(mapStateToProps, actions)(ShoppingBasket);
我的减速器:
export default function shoppingBasket(
state = {
list: [],
},
action
) {
let tmp = [];
switch (action.type) {
case SHOPPING_BASKET_ADD:
return { list: [...state.list, action.payload.product] };
case SHOPPING_BASKET_REMOVE:
tmp = state.list;
tmp.splice(action.payload.index, 1);
return { list: tmp };
default:
return state;
}
}
当在 redux 状态下插入元素时,我的组件成功更新,但是当我单击按钮并调用时 removeFromBasket
元素已从 redux 状态中删除,但组件不应更新。
splice
不会 return 新数组,而只会改变调用它的数组,因此对 list
属性 的引用不会改变。在 Redux 中,你必须始终 return 新状态对象(永远不要改变状态),否则你的组件将不会更新,因为它在内部对当前和下一个属性进行浅比较,所以如果引用没有改变,它认为它们相等并阻止组件 re-render。您可以像这样从 Redux way
中的数组中删除项目:
case SHOPPING_BASKET_REMOVE:
return { list: [
...state.list.slice(0, action.payload.index),
...state.list.slice(action.payload.index + 1)
]
}
我在从 redux 状态删除元素时更新组件时遇到问题。
我的组件:
const mapStateToProps = state => ({
products: state.shoppingBasket.list,
});
const ShoppingBasket = React.createClass({
propTypes: {
removeProduct: React.PropTypes.func.isRequired,
products: React.PropTypes.array,
open: React.PropTypes.func.isRequired,
},
removeFromBasket(index, name) {
this.props.removeProduct(index);
},
render() {
return (
<div>
{this.props.products.map((product, index) => (
<div key={index}>
product.name
<button onClick={() => this.RemoveFromBasket(index)}
</div>
);
)}
</div>
);
},
});
export default connect(mapStateToProps, actions)(ShoppingBasket);
我的减速器:
export default function shoppingBasket(
state = {
list: [],
},
action
) {
let tmp = [];
switch (action.type) {
case SHOPPING_BASKET_ADD:
return { list: [...state.list, action.payload.product] };
case SHOPPING_BASKET_REMOVE:
tmp = state.list;
tmp.splice(action.payload.index, 1);
return { list: tmp };
default:
return state;
}
}
当在 redux 状态下插入元素时,我的组件成功更新,但是当我单击按钮并调用时 removeFromBasket
元素已从 redux 状态中删除,但组件不应更新。
splice
不会 return 新数组,而只会改变调用它的数组,因此对 list
属性 的引用不会改变。在 Redux 中,你必须始终 return 新状态对象(永远不要改变状态),否则你的组件将不会更新,因为它在内部对当前和下一个属性进行浅比较,所以如果引用没有改变,它认为它们相等并阻止组件 re-render。您可以像这样从 Redux way
中的数组中删除项目:
case SHOPPING_BASKET_REMOVE:
return { list: [
...state.list.slice(0, action.payload.index),
...state.list.slice(action.payload.index + 1)
]
}