我如何在react router dom操作中调度redux/toolkit操作?

问题描述 投票:0回答:1

这是我的路由器

const router = createBrowserRouter([
  {
    path: "/",
    element: <MainLayout />,
    errorElement: <Error />,
    children: [
      {
        path: "/inventory",
        element: <Inventory />,
      },
      {
        path: "/inventory/:inventoryId",
        element: <InventoryItem />,
        action: inventoryAction
      },
    ],
  }
]);

在库存物品内。我导出了 inventoryAction。由于此操作不在组件内部,因此我无法调度

useCreateNewItemMutation
操作

export const inventoryAction = async ({ request }: any) => {
  const data = await request.formData();
  let dataToSubmit = {
    unitName: data.get("unitName"),
    itemType: data.get("itemType"),
    price: data.get("price"),
    unitCount: data.get("unitCount"),
    inventoryId: data.get("inventoryId"),
  };
  //store.dispatch(useCreateNewItemMutation(dataToSubmit)) // HOW CAN I DISPATCH
  return null;
};


const InventoryItem = ({ params }: any) => {
  const { inventoryId } = useParams();

  const [addItemModalActive, setAddItemModalActive] = useState(false);

  return (
    <div>
     
            <Form
              method="post"
              action={`/inventory/${inventoryId}`}
              className="flex flex-col w-1/2"
            >
              <label className="text-sm text-gray-500 mb-2" htmlFor="item name">
                Item name
              </label>
              <input
                placeholder="Enter Item Name"
                id="item name"
                name="unitName"
                className="border rounded w-full mb-4 p-2 text-sm"
              ></input>

              <label className="text-sm text-gray-500 mb-2" htmlFor="item type">
                Item type
              </label>
              <input
                placeholder="Eg food,drink..."
                id="item type"
                name="itemType"
                className="border rounded w-full mb-4 p-2 text-sm"
              ></input>
            </Form>

    </div>
  );
};

正如您在 inventoryAction 函数中看到的,我想调度

useCreateNewItemMutation
操作。

我怎样才能做到这一点?

这里是商店.ts

const store = configureStore({
  reducer: {
    [apiSlice.reducerPath]: apiSlice.reducer,
    auth: authSliceReducer,
    organization: organizationSliceReducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(apiSlice.middleware),
  devTools: true,
});

export const apiSlice = createApi({
  baseQuery,
  tagTypes: ["User", "Inventory", "Item"],
  endpoints: (builder) => ({}),
});

这是导出变异函数的文件

export const itemApiSlice = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    createNewItem: builder.mutation({
      query: (data) => ({
        url: `http://localhost:3000/item`,
        method: "POST",
        body: data,
      }),
      
    }),
  }),
});

export const { useCreateNewItemMutation } = itemApiSlice;
reactjs redux redux-toolkit
1个回答
0
投票

您无法在 React 组件和自定义 React hook 之外调用 React hook。在加载器中,您可以手动将操作直接分派到商店。这里的关键是您不能使用端点生成的 React hook,但您可以手动启动一个。

示例:

import { store } from '../path/to/store';
import { itemApiSlice } from '../path/to/itemApiSlice';

export const inventoryAction = async ({ request }: any) => {
  const data = await request.formData();

  const dataToSubmit = {
    unitName: data.get("unitName"),
    itemType: data.get("itemType"),
    price: data.get("price"),
    unitCount: data.get("unitCount"),
    inventoryId: data.get("inventoryId"),
  };

  store.dispatch(
    itemApiSlice.endpoints.createNewItem.initiate(dataToSubmit)
  );

  return null;
};
© www.soinside.com 2019 - 2024. All rights reserved.