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

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

How to use retrieved data from post request in JSX

问题

以下是翻译好的部分:

const handleVerifyData = async() => {
    const verifyCall = await reservationsService.verifyQueueReservations(filteredReservationIds)
    const verifiedData = verifyCall.data
    return verifiedData 
}

<Modal
      isOpen={modals['carOnPlaceModal']?.isOpened ?? false}
      onClose={handleClose}
      styles={{
        width: "500px",
        bodyPadding: "28px 30px"
      }}
    >
        {
          verifiedData?.map(info => {
            return <Flex key={info.reservationId} style={{ flexDirection: "row", height: "40%", justifyContent: "space-evenly", alignItems: "flex-start" }}>
              <Flex style={{ display: "flex", flexDirection: "column" }}>
                <Text mb="10px">{info?.vehicleMark} {info?.vehicleModel} ({info?.vehicleBodyType})</Text>
                <CarNumberBox title={info.vehicleGovNumber} />
              </Flex>
              <Flex style={{ display: "flex", flexDirection: "column" }}>
                <Text fontSize="base" mb="10px">{T("notifications.car_on_place.form.select_box")}</Text>
                <ChakraSelect
                  value={selectedBoxes[info.reservationId]}
                  onChange={async (e: any) => {
                    const boxNumber: number = parseInt(e.target.value);
                    const res: AxiosResponse<any> =
                      await reservationsService.getCheckboxAvailability(info.reservationId, boxNumber);
                    const updatedSelectedBoxes: any = { ...selectedBoxes };

                    // 如果框被占用但车辆未被清洗
                    const hasWarning: boolean = res.data?.data?.warning ?? false;
                    // 如果框被占用但车辆正在清洗
                    const hasError: boolean = res.data?.data?.error ?? false;

                    updatedSelectedBoxes[info.reservationId] = boxNumber;

                    if (hasWarning) {

                      toggleModal(
                        "confirmationModal",
                        true,
                        {
                          title: `您确定要更改为 ${boxNumber} 箱吗?`,
                          handleSubmit: () => {
                            setSelectedBoxes(updatedSelectedBoxes)
                            toggleModal("confirmationModal", false, { title: "" })
                          }
                        }
                      )
                      return;
                    }
                    if (hasError) {
                      toast.error(T("general.error"))
                      console.log('框警告');
                      return;
                    }

                    setSelectedBoxes(updatedSelectedBoxes);
                  }}
                >
                  {Array(info?.boxCount).fill(0).map((option: any, index: number) => {
                    return <option key={index} value={index + 1}>#{index + 1}</option>;
                  })}
                </ChakraSelect>
              </Flex>
            </Flex>
          })
        }
</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:

const handleVerifyData = async() =&gt; {
const verifyCall = await reservationsService.verifyQueueReservations(filteredReservationIds)
const verifiedData = verifyCall.data
return verifiedData 
}
&lt;Modal
isOpen={modals[&#39;carOnPlaceModal&#39;]?.isOpened ?? false}
onClose={handleClose}
styles={{
width: &quot;500px&quot;,
bodyPadding: &quot;28px 30px&quot;
}}
&gt;
{
verifiedData?.map(info =&gt; {
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;
&lt;Flex style={{ display: &quot;flex&quot;, flexDirection: &quot;column&quot; }}&gt;
&lt;Text mb=&quot;10px&quot;&gt;{info?.vehicleMark} {info?.vehicleModel} ({info?.vehicleBodyType})&lt;/Text&gt;
&lt;CarNumberBox title={info.vehicleGovNumber} /&gt;
&lt;/Flex&gt;
&lt;Flex style={{ display: &quot;flex&quot;, flexDirection: &quot;column&quot; }}&gt;
&lt;Text fontSize=&quot;base&quot; mb=&quot;10px&quot;&gt;{T(&quot;notifications.car_on_place.form.select_box&quot;)}&lt;/Text&gt;
&lt;ChakraSelect
value={selectedBoxes[info.reservationId]}
onChange={async (e: any) =&gt; {
const boxNumber: number = parseInt(e.target.value);
const res: AxiosResponse&lt;any&gt; =
await reservationsService.getCheckboxAvailability(info.reservationId, boxNumber);
const updatedSelectedBoxes: any = { ...selectedBoxes };
// If the box is taken but it  car is not being washed
const hasWarning: boolean = res.data?.data?.warning ?? false;
// If the box is taken but it the car is being washed
const hasError: boolean = res.data?.data?.error ?? false;
// const hasValidationError: boolean = Object.values(updatedSelectedBoxes).some((e: any) =&gt; e === boxNumber) ?? false;
updatedSelectedBoxes[info.reservationId] = boxNumber;
if (hasWarning) {
toggleModal(
&quot;confirmationModal&quot;,
true,
{
title: `დარწმუნებული ხართ, რომ გსურთ ${boxNumber} ბოქსის შეცვლა`,
handleSubmit: () =&gt; {
setSelectedBoxes(updatedSelectedBoxes)
toggleModal(&quot;confirmationModal&quot;, false, { title: &quot;&quot; })
}
}
)
return;
// If denied pass () =&gt; {}
// If accepted
//const updatedSelectedBoxes: any = { ...selectedBoxes };
// If CheckBoxAvailability returns no warning or errors change the value 
// updatedSelectedBoxes[info.reservationId] = e.value;
// setSelectedBoxes(updatedSelectedBoxes);
}
if (hasError) {
toast.error(T(&quot;general.error&quot;))
console.log(&#39;Warning for box&#39;);
return;
}
// // If CheckBoxAvailability returns no warning or errors change the value 
setSelectedBoxes(updatedSelectedBoxes);
}}
// options={generateOptions(info?.boxCount || 0)}
&gt;
{Array(info?.boxCount).fill(0).map((option: any, index: number) =&gt; {
return &lt;option key={index} value={index + 1}&gt;#{index + 1}&lt;/option&gt;;
})}
&lt;/ChakraSelect&gt;
&lt;/Flex&gt;
&lt;/Flex&gt;
})
}
&lt;/Modal&gt;

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

答案1

得分: 2

在渲染中使用此值时:

verifiedData?.map(info => {

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

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

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

const handleVerifyData = async () => {
  const verifyCall = await reservationsService.verifyQueueReservations(filteredReservationIds);
  const verifiedData = verifyCall.data;
  setVerifiedData(verifiedData);
}

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

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

const verifiedData = verifyCall.data;

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

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

Since you're using this value in the rendering:

verifiedData?.map(info =&gt; {

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

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:

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

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:

const verifiedData = verifyCall.data;

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

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

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:

确定