如何在JSX中使用从POST请求检索到的数据。

huangapple go评论91阅读模式
英文:

How to use retrieved data from post request in JSX

问题

以下是翻译好的部分:

  1. const handleVerifyData = async() => {
  2. const verifyCall = await reservationsService.verifyQueueReservations(filteredReservationIds)
  3. const verifiedData = verifyCall.data
  4. return verifiedData
  5. }
  6. <Modal
  7. isOpen={modals['carOnPlaceModal']?.isOpened ?? false}
  8. onClose={handleClose}
  9. styles={{
  10. width: "500px",
  11. bodyPadding: "28px 30px"
  12. }}
  13. >
  14. {
  15. verifiedData?.map(info => {
  16. return <Flex key={info.reservationId} style={{ flexDirection: "row", height: "40%", justifyContent: "space-evenly", alignItems: "flex-start" }}>
  17. <Flex style={{ display: "flex", flexDirection: "column" }}>
  18. <Text mb="10px">{info?.vehicleMark} {info?.vehicleModel} ({info?.vehicleBodyType})</Text>
  19. <CarNumberBox title={info.vehicleGovNumber} />
  20. </Flex>
  21. <Flex style={{ display: "flex", flexDirection: "column" }}>
  22. <Text fontSize="base" mb="10px">{T("notifications.car_on_place.form.select_box")}</Text>
  23. <ChakraSelect
  24. value={selectedBoxes[info.reservationId]}
  25. onChange={async (e: any) => {
  26. const boxNumber: number = parseInt(e.target.value);
  27. const res: AxiosResponse<any> =
  28. await reservationsService.getCheckboxAvailability(info.reservationId, boxNumber);
  29. const updatedSelectedBoxes: any = { ...selectedBoxes };
  30. // 如果框被占用但车辆未被清洗
  31. const hasWarning: boolean = res.data?.data?.warning ?? false;
  32. // 如果框被占用但车辆正在清洗
  33. const hasError: boolean = res.data?.data?.error ?? false;
  34. updatedSelectedBoxes[info.reservationId] = boxNumber;
  35. if (hasWarning) {
  36. toggleModal(
  37. "confirmationModal",
  38. true,
  39. {
  40. title: `您确定要更改为 ${boxNumber} 箱吗?`,
  41. handleSubmit: () => {
  42. setSelectedBoxes(updatedSelectedBoxes)
  43. toggleModal("confirmationModal", false, { title: "" })
  44. }
  45. }
  46. )
  47. return;
  48. }
  49. if (hasError) {
  50. toast.error(T("general.error"))
  51. console.log('框警告');
  52. return;
  53. }
  54. setSelectedBoxes(updatedSelectedBoxes);
  55. }}
  56. >
  57. {Array(info?.boxCount).fill(0).map((option: any, index: number) => {
  58. return <option key={index} value={index + 1}>#{index + 1}</option>;
  59. })}
  60. </ChakraSelect>
  61. </Flex>
  62. </Flex>
  63. })
  64. }
  65. </Modal>

"verifiedData" 是您想要在该函数之外自由访问的值。谢谢您提前的感谢。

英文:

I am retrieving data from post request which is simple object. In order to retrieve data i need to use await operator and as far as I know await can be used only in async functions. If I use async function then how to access that data outside that async function in my JSX ? or is it possible to retrieve data from post request without await ? Here is the code:

  1. const handleVerifyData = async() =&gt; {
  2. const verifyCall = await reservationsService.verifyQueueReservations(filteredReservationIds)
  3. const verifiedData = verifyCall.data
  4. return verifiedData
  5. }
  6. &lt;Modal
  7. isOpen={modals[&#39;carOnPlaceModal&#39;]?.isOpened ?? false}
  8. onClose={handleClose}
  9. styles={{
  10. width: &quot;500px&quot;,
  11. bodyPadding: &quot;28px 30px&quot;
  12. }}
  13. &gt;
  14. {
  15. verifiedData?.map(info =&gt; {
  16. return &lt;Flex key={info.reservationId} style={{ flexDirection: &quot;row&quot;, height: &quot;40%&quot;, justifyContent: &quot;space-evenly&quot;, alignItems: &quot;flex-start&quot; }}&gt;
  17. &lt;Flex style={{ display: &quot;flex&quot;, flexDirection: &quot;column&quot; }}&gt;
  18. &lt;Text mb=&quot;10px&quot;&gt;{info?.vehicleMark} {info?.vehicleModel} ({info?.vehicleBodyType})&lt;/Text&gt;
  19. &lt;CarNumberBox title={info.vehicleGovNumber} /&gt;
  20. &lt;/Flex&gt;
  21. &lt;Flex style={{ display: &quot;flex&quot;, flexDirection: &quot;column&quot; }}&gt;
  22. &lt;Text fontSize=&quot;base&quot; mb=&quot;10px&quot;&gt;{T(&quot;notifications.car_on_place.form.select_box&quot;)}&lt;/Text&gt;
  23. &lt;ChakraSelect
  24. value={selectedBoxes[info.reservationId]}
  25. onChange={async (e: any) =&gt; {
  26. const boxNumber: number = parseInt(e.target.value);
  27. const res: AxiosResponse&lt;any&gt; =
  28. await reservationsService.getCheckboxAvailability(info.reservationId, boxNumber);
  29. const updatedSelectedBoxes: any = { ...selectedBoxes };
  30. // If the box is taken but it car is not being washed
  31. const hasWarning: boolean = res.data?.data?.warning ?? false;
  32. // If the box is taken but it the car is being washed
  33. const hasError: boolean = res.data?.data?.error ?? false;
  34. // const hasValidationError: boolean = Object.values(updatedSelectedBoxes).some((e: any) =&gt; e === boxNumber) ?? false;
  35. updatedSelectedBoxes[info.reservationId] = boxNumber;
  36. if (hasWarning) {
  37. toggleModal(
  38. &quot;confirmationModal&quot;,
  39. true,
  40. {
  41. title: `დარწმუნებული ხართ, რომ გსურთ ${boxNumber} ბოქსის შეცვლა`,
  42. handleSubmit: () =&gt; {
  43. setSelectedBoxes(updatedSelectedBoxes)
  44. toggleModal(&quot;confirmationModal&quot;, false, { title: &quot;&quot; })
  45. }
  46. }
  47. )
  48. return;
  49. // If denied pass () =&gt; {}
  50. // If accepted
  51. //const updatedSelectedBoxes: any = { ...selectedBoxes };
  52. // If CheckBoxAvailability returns no warning or errors change the value
  53. // updatedSelectedBoxes[info.reservationId] = e.value;
  54. // setSelectedBoxes(updatedSelectedBoxes);
  55. }
  56. if (hasError) {
  57. toast.error(T(&quot;general.error&quot;))
  58. console.log(&#39;Warning for box&#39;);
  59. return;
  60. }
  61. // // If CheckBoxAvailability returns no warning or errors change the value
  62. setSelectedBoxes(updatedSelectedBoxes);
  63. }}
  64. // options={generateOptions(info?.boxCount || 0)}
  65. &gt;
  66. {Array(info?.boxCount).fill(0).map((option: any, index: number) =&gt; {
  67. return &lt;option key={index} value={index + 1}&gt;#{index + 1}&lt;/option&gt;;
  68. })}
  69. &lt;/ChakraSelect&gt;
  70. &lt;/Flex&gt;
  71. &lt;/Flex&gt;
  72. })
  73. }
  74. &lt;/Modal&gt;

verifiedData is the value i wanna access outside that function freely. Thanks in advance.

答案1

得分: 2

在渲染中使用此值时:

  1. verifiedData?.map(info => {

那么这个值应该存在于state中,对吗?类似这样:

  1. const [verifiedData, setVerifiedData] = useState([]);

在这种情况下,尝试让渲染本身等待结果是错误的方法。相反,函数应该更新状态:

  1. const handleVerifyData = async () => {
  2. const verifyCall = await reservationsService.verifyQueueReservations(filteredReservationIds);
  3. const verifiedData = verifyCall.data;
  4. setVerifiedData(verifiedData);
  5. }

当状态更新时,组件将使用新数据重新渲染。

另外,要注意变量命名。你当前遮蔽了状态变量:

  1. const verifiedData = verifyCall.data;

随着时间的推移,这可能很容易导致混淆和错误。你可以完全消除遮蔽的变量:

  1. const handleVerifyData = async () => {
  2. const verifyCall = await reservationsService.verifyQueueReservations(filteredReservationIds);
  3. setVerifiedData(verifyCall.data);
  4. }
英文:

Since you're using this value in the rendering:

  1. verifiedData?.map(info =&gt; {

Then presumably this value exists in state, no? Something like this:

  1. const [verifiedData, setVerifiedData] = useState([]);

In which case trying to make the rendering itself wait for the result is the wrong approach. Instead, the function should update state:

  1. const handleVerifyData = async() =&gt; {
  2. const verifyCall = await reservationsService.verifyQueueReservations(filteredReservationIds);
  3. const verifiedData = verifyCall.data;
  4. setVerifiedData(verifiedData);
  5. }

When state is updated, the component will re-render with the new data.


As an aside, be careful with variable naming. You are currently shadowing the state variable here:

  1. const verifiedData = verifyCall.data;

Over time this could easily lead to confusion and bugs. You can eliminate the shadowed variable entirely:

  1. const handleVerifyData = async() =&gt; {
  2. const verifyCall = await reservationsService.verifyQueueReservations(filteredReservationIds);
  3. setVerifiedData(verifyCall.data);
  4. }

huangapple
  • 本文由 发表于 2023年7月17日 20:25:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76704432.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定