我有一个连接的组件,我正试图从中分发clear
动作,如下所示:
import {createElement} from 'react';
import reduce from 'lodash/fp/reduce';
import {connect} from 'react-redux';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faShoppingCart} from '@fortawesome/free-solid-svg-icons';
import {clear} from '../../action/cart';
import * as products from '../../data/items';
import Heading from '../Heading';
import styles from './styles.css';
import Item from '../Item';
const Cart = ({total, items}) => (
<div>
<button onClick={clear}>Clear all items</button>
<table className={styles.cartItems}>
<tbody>
{items.map(({...item}, id) =>
(<Item {...item} key={id} />))}
<tr>
<td colSpan={4}>
{items.length > 0 ?
<div className={styles.total}>${total}</div> :
<div>Your cart is empty</div>
}
</td>
</tr>
</tbody>
</table>
</div>
);
export default connect((state) => {
return {
items: state.cart.items,
total: reduce(
(sum, {id, quantity}) => sum + products[id].price * quantity,
0,
state.cart.items
).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'),
};
})(Cart);
由于某种原因,根本没有调用clear
的动作,而其他动作却被调用。在减速器中,它看起来像这样:
[CLEAR_ITEMS]: () => ({
items: [],
}),
答案 0 :(得分:0)
您需要提供从dispatcher
组件的Redux props
到<Cart />
的映射,方法是将其添加到对connect()
的调用中:
export default connect((state) => {
return {
items: state.cart.items,
total: reduce(
(sum, {id, quantity}) => sum + products[id].price * quantity,
0,
state.cart.items
).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'),
};
},
/* Add this */
(dispatch) => {
return {
dispatchClear : () => dispatch(clear())
}
})(Cart);
现在,您可以像这样调整clear()
组件,将<Cart/>
动作分派给减速器:
/* Add dispatchClear now that it's mapped to props of your Cart component */
const Cart = ({total, items, dispatchClear}) => (
<div>
<button onClick={dispatchClear}>Clear all items</button>
<table className={styles.cartItems}>
<tbody>
{items.map(({...item}, id) =>
(<Item {...item} key={id} />))}
<tr>
<td colSpan={4}>
{items.length > 0 ?
<div className={styles.total}>${total}</div> :
<div>Your cart is empty</div>
}
</td>
</tr>
</tbody>
</table>
</div>
);