**这是购物车导入和状态
const Cart = ({ cart, setActiveTab, removeFromCart, updateQuantity }) => {
const [selectedRows , setSelectedRows] = useState([]);
const [toggleCleared, setToggleCleared] = useState(false);
const [products, setProducts] = useState(cart.products) }
const columns = [
{
name: 'Product Name',
selector: 'name',
sortable: true,
},
{
name: 'Product Price',
selector: 'price',
sortable: true,
right: true,
},
{
name: 'Product Quantity',
selector: 'quantity',
sortable: true,
right: true,
cell: row => <Fragment><input type="number" className="form-control" value={row.quantity} onChange = {(e)=>updateQuantity( row.id,strong text e.target.value)}/></Fragment>
},
{
name: 'Subtotal',
selector: 'quantity',
sortable: true,
right: true,
cell: row => <Fragment>{row.quantity * row.price}</Fragment>
},
{
name: 'Actions',
selector: 'quantity',
sortable: true,
right: true,
cell: row => <Fragment><i className="fa fa-trash" aria-hidden="true" onClick = {(e)=>removeFromCart(row.id)}></i></Fragment>
},
];
const contextActions = useMemo(() => {
const handleDelete = () => {
selectedRows.forEach(item=>{
console.log(item, 'item')
removeFromCart(products, products.indexOf(item))
});
setProducts(products);
setToggleCleared(!toggleCleared);
console.log('handleDelete', products)
};
return <i className="fa fa-trash" key="delete" onClick={handleDelete} style={{ backgroundColor: 'red' }} ></i>;
});
当我们选择行时,此代码设置所选行
function rowSelection (rows) =>{
setSelectedRows(rows.selectedRows);
}
return ( <DataTable
title="Cart Products"
columns={columns}
data={products}
selectableRows
onSelectedRowsChange={rowSelection}
clearSelectedRows={toggleCleared}
contextActions={contextActions} />
)
**这是我的购物车组件,它工作得很好,但当redux状态发生变化时,它不会自我更新。。我可以在控制台中看到redux状态,它完全改变了,但数据表没有重新发送
const〔products,setProducts〕=useState(cart.products(}这只适用于初始渲染(称为初始状态(。渲染完成后,useState不会调用。所以只需将cart.products传递到数据表
function rowSelection (rows) =>{
setSelectedRows(rows.selectedRows);
}
return ( <DataTable
title="Cart Products"
columns={columns}
data={cart.products}
selectableRows
onSelectedRowsChange={rowSelection}
clearSelectedRows={toggleCleared}
contextActions={contextActions} /> )