gpt4 book ai didi

javascript - 在连接的组件中调度一个 Action

转载 作者:行者123 更新时间:2023-11-30 06:21:20 27 4
gpt4 key购买 nike

我有一个连接的组件,我正尝试从中分派(dispatch) 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 的操作根本没有被调用,但其他操作却被调用。在 reducer 中它看起来像这样:

[CLEAR_ITEMS]: () => ({
items: [],
}),

最佳答案

您需要提供来自 redux dispatcher 的映射至 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/> 对您的 reducer 采取行动像这样的组件:

/* 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>
);

关于javascript - 在连接的组件中调度一个 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52883499/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com