如何在react router dom中的单个路由中使用多个操作?

Abi*_*san 7 reactjs react-router

我在不同的组件中有两种形式。我正在另一个组件中显示结果。我正在使用<Form>来自react-router-dom. 并使用获取数据action。如果我采取一项行动,效果很好。所以我尝试添加一个额外的action,比如,

{
  path: '/show-result`,
  element: <ShowResult />,
  action: actionFromFirstComponent,
  action: actionFromSecondComponent
}
Run Code Online (Sandbox Code Playgroud)

它没有按预期工作。我也尝试过action: [actionFromFirstComponent, actionFromSecondComponent]。但react-router-dom引发了我的handler is not a function错误。

我尝试在谷歌的反应路由器路由中搜索多个操作。但是,它只展示了如何为一个组件设置多个路由。

Dre*_*ese 9

您只能执行一个操作。单个操作应该获取额外的数据,以便它可以有条件地应用一种或另一种操作逻辑。一种方法是附加一个隐藏的 id 字段,该字段将formData在提交表单时与 一起提交。该操作应读取此字段值并有条件地应用正确的操作逻辑。

例子:

const multiFormAction = async (actionArg) => {
  const formData = await actionArg.request.formData();
  const formId = formData.get("form-id");

  switch (formId) {
    case "form 1":
      // This is form 1 logic
      return actionFromFirstComponent(actionArg); // <-- pass action arg through

    case "form 2":
      // This is form 2 logic
      return actionFromSecondComponent(actionArg); // <-- pass action arg through

    default:
      // Form was submitted without an id
      // What to do... throw or return error? Ignore? You decide.
  }
};
Run Code Online (Sandbox Code Playgroud)
{
  path: '/show-result`,
  element: <ShowResult />,
  action: multiFormAction,
}
Run Code Online (Sandbox Code Playgroud)
...

<Form method="post">
  <input name="form-id" hidden defaultValue="form 1" />
  ...
  <button type="submit">Submit</button>
</Form>

...

<Form method="post">
  <input name="form-id" hidden defaultValue="form 2" />
  ...
  <button type="submit">Submit</button>
</Form>

...
Run Code Online (Sandbox Code Playgroud)

编辑如何在react-router-dom中使用单个路由中的多个操作