从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状态中删除,但是commponent不应更新。
答案 0 :(得分:1)
splice
不会返回新数组但只会改变它所调用的数组,因此引用list
属性不会发生变化。在Redux中,您必须始终返回新的状态对象(从不改变状态),否则您的组件将不会更新,因为在内部它会对当前属性和下一个属性进行浅层比较,因此如果引用未被更改,则认为它们相等并阻止组件重新呈现。您可以在Redux way
中删除数组中的项目,如下所示:
case SHOPPING_BASKET_REMOVE:
return { list: [
...state.list.slice(0, action.payload.index),
...state.list.slice(action.payload.index + 1)
]
}