gpt4 book ai didi

javascript - 为什么更新的状态没有反射(reflect)在事件监听器中 : React Native, Hooks

转载 作者:行者123 更新时间:2023-12-03 07:08:08 25 4
gpt4 key购买 nike

我正在使用钩子(Hook)来更新状态。在我的代码中,我有一个 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 (appState === "active" && nextAppState.match(/inactive|background/)) {
console.log("App has come to background!")
}
setAppState(nextAppState)
}
//appState updated here
console.log(appState, "app state")
return <View />
}

最佳答案

在您的代码中 appState 是 stale closure the linter应该告诉你你缺少依赖项。
我认为以下将起作用

const _handleAppStateChange = useCallback(
(nextAppState) =>
//use callback for state setter so you don't
// create needless dependency or (as you did)
// create a stale closure
setAppState((currentAppState) => {
//logs current appstate
console.log(currentAppState, 'app state');
if (
currentAppState.match(/inactive|background/) &&
nextAppState === 'active'
) {
console.log('App has come to the foreground!');
activateRealtime();
} else if (
currentAppState === 'active' &&
nextAppState.match(/inactive|background/)
) {
console.log('App has come to background!');
}
return nextAppState;
}),
//only pass function as _handleAppStateChange
// on mount by providing empty dependency
[]
);
useEffect(() => {
AppState.addEventListener(
'change',
_handleAppStateChange
);
//clean up code when component unmounts
return () =>
AppState.removeEventListener(
'change',
_handleAppStateChange
);
//_handleAppStateChange is a dependency but useCallback
// has empty dependency so it is only created on mount
}, [_handleAppStateChange]);

关于javascript - 为什么更新的状态没有反射(reflect)在事件监听器中 : React Native, Hooks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62772776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com