简体   繁体   English

使用 setTimeout 和访问 state 在 React Native 中不起作用

[英]Using setTimeout and accessing state is not working in React Native

I am trying to have a setTimeout function call a method that works with some state but no matter what I do, the state variable is always undefined.我正在尝试让 setTimeout function 调用一种适用于某些 state 的方法,但无论我做什么,state 变量始终未定义。

// recordingObj is an instance of Expo-AV's `RecordingObject`
const [recordingObj, setRecording] = useState();
let noSpeechTimer = null;

async function startRecording() {
      const { recording } = await Audio.Recording.createAsync(Audio.RecordingOptionsPresets.HIGH_QUALITY);
      setRecording(recording);

      noSpeechTimer = setTimeout(()=> {
        console.log("NO SPEECH DETECTED")
        stopRecording();
      }, 5000));
}

async function stopRecording() {
    await recordingObj.stopAndUnloadAsync(); // <-- Errors here. `recording` is undefined
    setRecording(undefined);
    ...
}

I have tried setting noSpeechTimer up with useRef() , that didnt work.我尝试使用useRef()设置noSpeechTimer ,但没有用。 I tried creating a second variable for recordingObj and setting it up with useRef() and then calling recordingObjRef.current.stopAndUnloadAsync() and that didnt work.我尝试为 recordingObj 创建第二个变量并使用useRef()进行设置,然后调用recordingObjRef.current.stopAndUnloadAsync()但这没有用。 Im really stumped here as to whats happening.对于发生的事情,我真的很困惑。

Calling a setState function does two things:调用setState function 会做两件事:

  • Update the value of the state for the next render为下一次渲染更新 state 的值
  • Trigger a new render触发新的渲染

This means that the updated value from setState(value) will not be available until the next render.这意味着来自setState(value)的更新值在下一次渲染之前将不可用。

Your case can be solved with a ref:您的案例可以通过参考解决:


const recordingRef = useRef(null);

// ...
recordingRef.current = recording;

// ...

if (recordingRef.current)
   recordingRef.current.stopAndUnloadAsync()

recordingRef.current = null;

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

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