axios 为什么我的删除功能无法正常工作?

a0x5cqrl  于 2022-11-05  发布在  iOS
关注(0)|答案(1)|浏览(124)

所以我几乎完成了我的MERN与Redux/Toolkit,我已经完成了创建,读取,和更新。我也可以删除一个产品,但它不工作的方式,我想。
因此,当我删除item 1时,会删除表的最后一行。在此图像中,我将尝试删除item 1
Before I click
单击项目1后,将移除项目3
After I click
但是当我刷新它的时候它会自动纠正
After refresh/reload
apiCalls.js

export const deleteProduct = async (id, dispatch) => {
    dispatch(deleteProductStart());
    try {
      const res = await publicRequest.delete(`/products/${id}`);
      dispatch(deleteProductSuccess(res.data));
    } catch (err) {
      dispatch(deleteProductFailure());
    }
  };

MyProduct.js

const MyProducts = () => {
  const {products, isFetching, isError} = useSelector((state) => state.product)
  const dispatch = useDispatch()

  const handleDelete = (id) => {
    deleteProduct(id, dispatch);
  };

  useEffect(() =>{
    getProduct(dispatch);
  },[dispatch])

  return (
    <Box>
        <Navbar />
        <Box  sx={{display: {xs: 'none', md: 'flex'}, padding: '20px', flexDirection: 'column'}}>
          <Typography variant="h5" fontWeight={700}>My Products</Typography>
          <TableContainer component={Paper}>
          <Table sx={{ minWidth: 600 }} aria-label="simple table">
          <TableHead>
            <TableRow bgcolor="skyblue">
              <TableCell align='center'>Product</TableCell>
              <TableCell align='center'>Image</TableCell>
              <TableCell align='center'>Price</TableCell>
              <TableCell align='center'>Action</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {products.map((product) => (
              <TableRow
                key={product._id}
              >
                <TableCell align='center' component="th" scope="row">{product.title}</TableCell>
                <TableCell align='center'><Box component="img" sx={{width: '80px', height: '80px', borderRadius: '10px', objectFit: 'contain'}} src={product.productImage}/></TableCell>
                <TableCell align='center'>Php {product.price}</TableCell> 
                <TableCell align='center' bgcolor="skyblue" >
                  <Box sx={{display: 'flex', alignItems:'center', justifyContent: 'center', gap: "10px"}}>
                      <Link to={`/editproduct/${product._id}`}>
                        <Button variant="contained">Edit</Button>
                      </Link>
                      <Button onClick={() => handleDelete(product._id)} color="error" variant="contained">Delete</Button>
                  </Box>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>
        </Box>

    </Box>
  )
}

productSlice.js

import { createSlice } from "@reduxjs/toolkit";

export const productSlice = createSlice({
    name: 'product',
    initialState: {
        products: [],
        isFetching: false,
        isError: false
    },
    reducers: {
            deleteProductStart: (state) => {
            state.isFetching = true
            state.isError = false
          },
          deleteProductSuccess: (state, action) => {
            state.isFetching = false;
            state.products.splice(
              state.products.findIndex((item) => item._id === action.payload),
              1
            );
          },
          deleteProductFailure: (state) => {
            state.isFetching = false
            state.isError = true
          },

    }
})

export const {   
    deleteProductStart,
    deleteProductSuccess,
    deleteProductFailure,

  } = productSlice.actions

  export default productSlice.reducer
8i9zcol2

8i9zcol21#

deleteProductSuccess: (state, action) => {
            state.isFetching = false;
            state.products.splice(
              state.products.findIndex((item) => item._id === action.payload),
              1
            );
          },

在此代码块中,您将按索引查找产品,并将action.payload视为项目ID。您将响应中的数据作为操作进行传递。

dispatch(deleteProductSuccess(res.data));

因此item._id === action.payload将始终失败。findByIndex将返回-1splice(-1, 1)将删除最后一个元素。
1.修复action.payload将解决此问题。
1.您必须考虑项目不存在时的情况。目前正在删除最后一个项目。

相关问题