axios 应用程序崩溃- React Redux -无法正确获取参数

qzwqbdag  于 2023-10-18  发布在  iOS
关注(0)|答案(1)|浏览(122)

我目前在React Redux应用程序中面临着从愿望列表中删除项目的问题。我已经实现了一个功能,用户可以将项目添加到他们的愿望清单中,但是当他们试图删除一个项目时,我遇到了一个问题,即向我的删除函数传递正确的参数。
下面是我的设置的简要概述:
我正在使用React with Redux进行状态管理。用户可以成功添加愿望清单项目。当我试图删除一个愿望清单项目时,问题出现了。发行日期:
我尝试将userId和wishlistItemId作为参数传递给我的WishList DeleteWishEl函数,该函数将执行一个API调用以从服务器中删除该项。但是,wishlistItemId参数在到达API调用时似乎未定义。
下面是我的代码片段:

// Inside Wishlist.jsx component
const handleDeleteWish = async (userId, wishlistItemId) => {
  try {
    console.log("userId:", userId);
    console.log("wishlistItemId:", wishlistItemId);

    // API call to delete wishlist item
    await dispatch(handleDeleteWishEl({ userId, wishlistItemId }));
  } catch (error) {
    console.error("Error removing element from wishlist:", error);
  }
};

这里是我获取参数的地方,我正在传递给deletewish func:

{userWishlist.map((userWishEl) => {
        const itemPercentage = (userWishEl.price / userMoneybox.totalAmount) * 100;
        const itemDiff = userWishEl.price - userMoneybox.totalAmount;

        return (
          <Row key={userWishEl._id} className="mb-4">
            <Button
              onClick={() => handleExpand(userWishEl._id)}
              aria-controls={`collapse-wishEl-${userWishEl._id}`}
              aria-expanded={expandedItems[userWishEl._id]}
              variant="outline-primary"
            >
              <h5>{userWishEl.content}</h5>
              <p>{userWishEl.price} $(US)</p>
            </Button>

            <Collapse in={expandedItems[userWishEl._id]}>
              <div id={`collapse-wishEl-${userWishEl._id}`}>
                <p>{userWishEl.description}</p>

                <p className={`border rounded p-2`}>
                  {userWishEl.price > userMoneybox.totalAmount
                    ? ` You need to save ${itemDiff} $(US) to afford this item`
                    : `You should use the ${itemPercentage.toFixed(
                        2
                      )}% of your total Moneybox to afford
                  this item`}
                </p>
                <div className="d-flex align-items-center gap-3">
                  <Button
                    variant="danger"
                    onClick={() => handleDeleteWish(user._id, userWishEl._id)}
                    disabled={loadingDelete}
                  >
                    {loadingDelete ? "Removing..." : "Delete"}
                  </Button>
                  <Button variant="outline-warning">Edit</Button>
                </div>
              </div>
            </Collapse>
          </Row>
        );
      })}

我可以看到userId被正确记录,但wishlistItElId在到达API调用时似乎未定义。
下面是我的Reducer的一个片段:

export const handleDeleteWishEl = createAsyncThunk(
  "user/wishlist/delete",
  async ({ userId, wishlistElId }, thunkAPI) => {
    try {
      console.log("userId inside handleDeleteWishEl:", userId);
      console.log("wishlistItemId inside handleDeleteWishEl:", wishlistElId);

      const response = await axios.delete(
        `${process.env.REACT_APP_SERVERBASE_URL}/users/${userId}/wishlist/${wishlistElId}/delete`
      );
      return response.data;
    } catch (error) {
      return thunkAPI.rejectWithValue(error.message);
    }
  }
);

以及我是如何管理切片的

const wishlistSlice = createSlice({
  name: "wishlist",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(handleDeleteWishEl.pending, (state) => {
        state.loading = true;
      })
      .addCase(handleDeleteWishEl.fulfilled, (state, action) => {
        state.loading = false;
        state.wishElDeleted = action.payload;
      })
      .addCase(handleDeleteWishEl.rejected, (state, action) => {
        state.loading = false;
        state.errorWishEl = action.payload;
      })

      .addCase(getUserWishlist.pending, (state) => {
        state.loading = true;
      })
      .addCase(getUserWishlist.fulfilled, (state, action) => {
        state.loading = false;
        state.wishlist = action.payload;
      })
      .addCase(getUserWishlist.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      });
  },
});

export const wishlistState = (state) => state.wishlist.wishlist;
export default wishlistSlice.reducer;

我尝试过的:
我已经验证了wishlistItemId是在我调用wishListDeleteWish函数时定义的。我已经检查了我的Redux action和reducer,它们似乎配置正确。我已确保用于删除愿望清单项目的服务器端点正常工作。
请求帮助:
我将非常感谢任何关于可能导致此问题或如何有效调试它的见解或建议。如果你需要更多的代码或信息,请让我知道,我会提供。
提前感谢您的帮助!

3xiyfsfu

3xiyfsfu1#

问题

wishlistItemIdhandleDeleteWishEl action payload中传递:

await dispatch(handleDeleteWishEl({ userId, wishlistItemId }));

但是handleDeleteWishEl形实转换程序并没有从有效载荷中解构它。相反,它正在解构一个wishlistElId属性,这显然是未定义的,因为没有为该属性传递值。

export const handleDeleteWishEl = createAsyncThunk(
  "user/wishlist/delete",
  async (
    {
      userId,
      wishlistElId // <-- undefined
    },
    thunkAPI
  ) => {
    try {
      const response = await axios.delete(
        `${process.env.REACT_APP_SERVERBASE_URL}/users/${userId}/wishlist/${wishlistElId}/delete`
      );
      return response.data;
    } catch (error) {
      return thunkAPI.rejectWithValue(error.message);
    }
  }
);

解决方案

要么将wishlistElId传递给handleDeleteWishEl,要么解构传递的wishlistItemId

const handleDeleteWish = async (userId, wishlistItemId) => {
  try {
    // API call to delete wishlist item
    await dispatch(handleDeleteWishEl({ userId, wishlistItemId }));
  } catch (error) {
    console.error("Error removing element from wishlist:", error);
  }
};
export const handleDeleteWishEl = createAsyncThunk(
  "user/wishlist/delete",
  async ({ userId, wishlistItemId }, thunkAPI) => {
    try {
      const response = await axios.delete(
        `${process.env.REACT_APP_SERVERBASE_URL}/users/${userId}/wishlist/${wishlistItemId}/delete`
      );
      return response.data;
    } catch (error) {
      return thunkAPI.rejectWithValue(error.message);
    }
  }
);

const handleDeleteWish = async (userId, wishlistElId) => {
  try {
    // API call to delete wishlist item
    await dispatch(handleDeleteWishEl({ userId, wishlistElId }));
  } catch (error) {
    console.error("Error removing element from wishlist:", error);
  }
};
export const handleDeleteWishEl = createAsyncThunk(
  "user/wishlist/delete",
  async ({ userId, wishlistElId }, thunkAPI) => {
    try {
      const response = await axios.delete(
        `${process.env.REACT_APP_SERVERBASE_URL}/users/${userId}/wishlist/${wishlistElId}/delete`
      );
      return response.data;
    } catch (error) {
      return thunkAPI.rejectWithValue(error.message);
    }
  }
);

相关问题