如何使React元件能夠記錄右鍵點擊的變量,需要雙擊才能實現
P粉083785014
P粉083785014 2023-08-15 22:46:56
0
1
492
<p>我在我的專案中遇到了一個React元件的問題,當我在導航過程中需要點擊兩次才能正確記錄右鍵點擊的變數。以下是問題的詳細資訊和我的程式碼:</p> <p>我有一個React元件,表示課程課程導航系統。當我在導航選單中點擊一個課程時,它應該記錄所點擊課程的索引並啟動某些操作。然而,我注意到我需要點擊兩次才能正確記錄索引。 </p> <p>在元件內部,有一個名為handleOtp的函數,它處理啟動視訊播放和設定視訊存取OTP的邏輯。問題似乎源自於這個函數。 </p> <p>以下是handleOtp函數的簡化概述:</p> <pre class="lang-js prettyprint-override"><code>const handleOtp = async () => { try { const lessonId = course.lessons[clicked]?.video?.id; // 這是有問題的區域 const { data } = await axios.post("/api/videoOtp", { videoId: lessonId, username: user.username, ip, }); if (!data.otp && !data.playbackInfo) { return toast.error("影片OTP失敗!重新載入頁面"); } loadVideo({ otp: data.otp, playbackInfo: data.playbackInfo, configuration: { autoplay: true, }, container: container.current, }); } catch (err) { console.error(err); } }; </code></pre> <p>根據我的觀察,第一次點擊觸發了handleOtp函數,但點擊的索引錯誤,導致了意外的行為。第二次點擊最終記錄了正確的點擊索引,並按預期工作。 </p> <p>我已確保沒有可能引起問題的非同步狀態更新。我懷疑可能存在一個時間或狀態管理問題導致了這種行為,但我很難確定確切的原因。 </p> <p>我希望能夠理解為什麼會發生這種雙擊行為,以及如何確保在第一次點擊時記錄正確的點擊索引。非常感謝任何見解或建議。謝謝!</p> <p>我的 React 元件:</p> <pre class="brush:php;toolbar:false;"><StudentRoute>
<選單 defaultSelectedKeys={[點選]} inlineCollapsed={折疊} 樣式={{高度:“100%”}} > {course.lessons.map((課程,索引) => ( <項目 onClick={async()==> { setClicked(索引); setIsLoading(true); setSpin(真); setCheckoutVisibility(“無”); 檢查交易狀態(索引); setPaymentMethod("自助服務終端"); setKioskPhoneNumber(""); 處理Otp(); }} 鍵={索引} icon={<頭像>{索引1}} ></前> <p>嘗試使用console.log記錄點擊的變數:</p>
P粉083785014
P粉083785014

全部回覆(1)
P粉821231319

這是因為setState是非同步執行的。你在OnClick事件中設定了clicked,然後呼叫了handleOtp函數。在這種情況下,狀態還沒有更新,所以第一次點擊會得到錯誤的索引。

你只需要將index當作參數傳遞給handleOtp。不再需要setClicked

const handleOtp = async (index) => {}

<StudentRoute>
    <div className="row mt-2">
      <div className="lessons-menu">
        <Menu
          defaultSelectedKeys={[clicked]}
          inlineCollapsed={collapsed}
          style={{ height: "100%" }}
        >
          {course.lessons.map((lesson, index) => (
            <Item
              onClick={async () => {
                setIsLoading(true);
                setSpin(true);
                setCheckoutVisibility("none");
                checkTransactionStatus(index);
                setPaymentMethod("kiosk");
                setKioskPhoneNumber("");
                handleOtp(index);
              }}
              
              key={index}
              icon={<Avatar>{index + 1}</Avatar>}
            />
          ))}
        <Menu/>
      </div>
    </div>
<StudentRoute/>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!