redux 在useEffect内部触发分派仅一次

nfs0ujit  于 2023-11-19  发布在  其他
关注(0)|答案(1)|浏览(148)

我有这样一个组件,每当addressList中发生更改时,我只需要在useEffect中触发dispatch一次(与handleAddNewShippingAddresshandleEditShippingAddresshandleEditShippingAddress中的任何一个被触发时相同,这会导致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>
    );
}

字符串

af7jpaap

af7jpaap1#

这个逻辑可能应该从React中移除。你的动作可以是Redux Thunks,它处理外部请求的序列。

export function getShippingAddressList() { /* … */ }

export function addShippingAddress(newAddressData) {
  return async (dispatch, /* getState */) => {
    await doApiCallToAddShippingAddress(newAddressData);
    dispatch(getShippingAddressList());
  };
}

export function editShippingAddress(formData, shippingAddressId) {
  return async (dispatch, /* getState */) => {
    await doApiCallToEditShippingAddress(formData, shippingAddressId);
    dispatch(getShippingAddressList());
  };
}

export function removeShippingAddress(shippingAddressId) {
  return async (dispatch, /* getState */) => {
    await doApiCallToRemoveShippingAddress(shippingAddressId);
    dispatch(getShippingAddressList());
  };
}

字符串

相关问题