小编Mer*_*vzs的帖子

为什么更新的状态没有反映在事件侦听器中:React Native、Hooks

我正在使用钩子来更新状态。在我的代码中,我有一个 AppState 事件监听器,每当它触发时,我都会使用setAppState更新appState,但是事件监听器内的 appState 没有改变。但该值正在侦听器外部更新。谁能解释为什么会有这样的行为?

这是我的代码:

    import React, { FunctionComponent, useEffect, useState } from "react"
    import { View, AppState, AppStateStatus } from "react-native"
    const Test: FunctionComponent<any> = (props: any) => {
        const [appState, setAppState] = useState < AppStateStatus > (AppState.currentState)
    
        useEffect(() => {
            AppState.addEventListener("change", _handleAppStateChange)
        },[])
    
        const _handleAppStateChange = (nextAppState: AppStateStatus) => {
         //appState not Changing here
            console.log(appState, "app state")
            if (appState.match(/inactive|background/) && nextAppState === "active") {
                console.log("App has come to the foreground!")
                activateRealtime()
            } else if …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-native react-hooks

8
推荐指数
1
解决办法
3566
查看次数

标签 统计

javascript ×1

react-hooks ×1

react-native ×1

reactjs ×1