reactjs Action函数是在Remix js中执行POST请求的唯一方法吗?

aydmsdu9  于 2023-01-25  发布在  React
关注(0)|答案(1)|浏览(131)

我有一个应用程序,我可以上传一个csv,当我点击上传按钮时,我会以JSON格式获得该csv的内容。我的要求是,我希望暂停POST请求,直到我使用另一个模态组件确认上传。我所做的是,我在UI组件中创建了一个异步等待,并将Action函数返回的数据传递给该异步等待函数confirmHandler。这些是我在post中使用的方法。

export const action = async ({ request }: ActionArgs) => {
  // Do some other work and get the csv content as a string

  const csvDataString: string = formData.get("selected_csv") as string;

  let codeListUploadValidationMessage = "";

  // Do the code list validation

  if (codeListUploadValidationMessage) {
    // if there are validation errors
    return json(
      {
        errors: {
          message: codeListUploadValidationMessage,
        },
      },
      { status: 400 }
    );
  } else {
    // if there are no any validation errors do some work convert string into an object call 'result'
    // Then return the 'result' as a JSON
    return json({ result });
  }
};

export default function Index() {
  const actionData = useActionData<typeof action>();
  const [data, setData] = React.useState([]);
  const [submitted, setSubmitted] = React.useState(false);
  const [showConfirmSave, setShowConfirmSave] = React.useState(false);
 
  React.useEffect(() => {
    setData(actionData?.result)
    console.log("=== Log of data: ", data);
  }, [actionData?.result, data]);

  React.useEffect(() => {
    switch (transition.state) {
      case "submitting":
        if (!submitted) {
          setSubmitted(true);
        }
        break;

      case "idle":
        if (submitted && data) {
          setShowConfirmSave(true);
        }
        break;
    }
  }, [data, submitted, setShowConfirmSave, setSubmitted, transition]);

  const confirmHandler = async () => {
    await bulkUploadCodeList(data);
    setShowConfirmSave(false);
  };

  if (showConfirmSave) {
    return <Confirm onConfirm={confirmHandler} />;
  }

return(
    <div>
      <Form method="post">
        <button type="submit">Upload data</button>
      </Form>
    </div>  
  );
}


这就是confirm模态

import {
  Link,
} from "@remix-run/react";
import React from "react";

interface ConfirmProps {
  onConfirm: () => void;
}

export default function Confirm({ onConfirm }: ConfirmProps) {
  return (
    <div>
      <div>
        <h1>Are you sure you want to save the data?</h1>
      </div>
      <div>
        <button type="button" onClick={onConfirm}>Save</button>
      </div>
      <div>
        <Link to="/codes/uploadCodeList">
          <button type="button">Cancel</button>
        </Link>
      </div>
    </div>
  );
}

现在我可以得到确认模态时,我点击上传按钮,但异步等待函数不做任何POST请求到后端。我该如何解决这个问题?帮助将是非常感谢。

d4so4syb

d4so4syb1#

你应该使用useSubmit()钩子,这是你在Remix中编程提交的方式,所以在你的onConfirm()处理程序中,提示确认,如果是,调用submit(),否则调用event.preventDefault()
https://reactrouter.com/en/main/hooks/use-submit

相关问题