我有这样一个组件,每当addressList
中发生更改时,我只需要在useEffect
中触发dispatch
一次(与handleAddNewShippingAddress
或handleEditShippingAddress
或handleEditShippingAddress
中的任何一个被触发时相同,这会导致addressList
发生变化)。如果我将addressList
传递到依赖列表中,它会进入无限循环,因此,我将addressList字符串化并将其传递到dependency中。这种方法有时会导致对后端的额外请求。我如何才能实现不使用这种方法并在addressList
中更改时仅触发useEffect
一次?
function ShippingAddress() {
const dispatch = useDispatch()
const { isLoading, addressList, error } = useSelector(state => state.address)
const addressListString = JSON.stringify(addressList)
console.log(addressListString)
useEffect(() => {
// Triggers GET request
dispatch(getShippingAddressList())
}, [dispatch, addressListString])
// Triggers POST request
const handleAddNewShippingAddress = (newAddressData) => {
dispatch(addShippingAddress(newAddressData))
}
// Triggers PUT request
const handleEditShippingAddress = (formData, shippingAddressId) => {
dispatch(editShippingAddress(formData, shippingAddressId))
}
// Triggers DELETE request
const handleRemoveShippingAddress = (shippingAddressId) => {
dispatch(removeShippingAddress(shippingAddressId))
}
return (
<React.Fragment>
...
</React.Fragment>
);
}
字符串
1条答案
按热度按时间af7jpaap1#
这个逻辑可能应该从React中移除。你的动作可以是Redux Thunks,它处理外部请求的序列。
字符串