简体   繁体   English

无法使用 React 中的 useState 挂钩设置上一个代码 state

[英]Unable to set previousCode state using useState hook in React

I am new to react and javascript and cannot understand why setPreviousCode is not changing the state.我是新来的反应和 javascript 并且不明白为什么setPreviousCode没有改变 state。 I want to store the previous scanned text in previousCode .我想将以前扫描的文本存储在previousCode中。

import React, { useEffect, useState } from "react"
import { Html5Qrcode } from "html5-qrcode"
import { useCallback } from "react"

let html5QrCode
const brConfig = {
    fps: 10,
    qrbox: { width: 300, height: 150 },
    disableFlip: false,
}

export const Scanner = () => {
    const beep = new Audio("https://www.soundjay.com/buttons/beep-08b.mp3")

    const [previousCode, setPreviousCode] = useState(null)

    useEffect(() => {
        html5QrCode = new Html5Qrcode("reader")
        startScan()
    }, [])

    const startScan = useCallback(() => {
        console.log("imrunngin")
        const qrCodeSuccessCallback = (decodedText, decodedResult) => {
            if (previousCode !== decodedText) {
                beep.play()
                setPreviousCode(decodedText)
            }
        }
        html5QrCode.start(
            { facingMode: "environment" },
            brConfig,
            qrCodeSuccessCallback
        )
    }, [])

    const handleStop = () => {
        try {
            html5QrCode
                .stop()
                .then((res) => {
                    html5QrCode.clear()
                    console.log("stopped")
                })
                .catch((err) => {
                    console.log(err.message)
                })
        } catch (err) {
            console.log(err)
        }
    }

    return (
        <div style={{ position: "relative", backgroundColor: "#1E1E1E" }}>
            <div id="reader" width="100%" />
        </div>
    )
}

When you update a state property, with respect to its previous value , use the callback argument * of the state setter.当您更新 state 属性时,相对于其先前的值,使用 state 设置器的回调参数*。 Otherwise stale state values may be taken into account.否则可能会考虑陈旧的 state 值。

https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

Try with,尝试,

 const qrCodeSuccessCallback = (decodedText, decodedResult) => {
     setPreviousCode((previousCode)=> {
         if (previousCode !== decodedText) {
            beep.play()
            return decodedText;
         }
         return previousCode
     });
 }

Or even better (the state setter is pure ):甚至更好(state 设置器是的):

const qrCodeSuccessCallback = (decodedText, decodedResult) => {
     setPreviousCode((previousCode)=> (previousCode !== decodedText) ?decodedText:previousCode
     });
 }

 useEffect(()=>{
     beep.play();
 }, [previousCode]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM