[英]React native useEffect clean up not using the updated states properly
I have been scratching my head on something weird that happens during the clean up function of useEffect.我一直在为清理 useEffect 的 function 期间发生的一些奇怪的事情摸不着头脑。 Basically, in the clean up code, I invoke a updateStore() function to update store based on the boolean value of changeFlag.基本上,在清理代码中,我调用 updateStore() function 以根据 changeFlag 的 boolean 值更新存储。 However, the updateStore() and even the clean up function itself is not reflecting the updated state of changeFlag and I could not figure out why.但是,updateStore() 甚至清理 function 本身都没有反映 changeFlag 的更新 state ,我不知道为什么。
I tried to do a simple POC on a clean project thinking that it might be caused by some bug of my project but it is still having the same problem.我试图在一个干净的项目上做一个简单的 POC,认为它可能是由我的项目的一些错误引起的,但它仍然有同样的问题。
App.js应用程序.js
import React, {useState, useEffect} from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
const Test = ({navigation}) => {
//const { id } = route.params;
const [changeFlag, setChangeFlag] = useState(false);
useEffect(() => {
console.log(`Start: ${changeFlag}`);
return function cleanup () {
console.log(`Exiting: ${changeFlag}`);
updateStore();
};
}, []);
useEffect(() => {
console.log(`Flag changed! ${changeFlag}`);
})
const toggle = () => {
setChangeFlag(!changeFlag);
}
const updateStore = () => {
console.log(`Print flag ${changeFlag}`);
}
return (
<View style={styles.container}>
<Text>{changeFlag ? "True" : "False"} </Text>
<Button title={"Press toggle"} onPress={toggle}/>
</View>
);
}
const Home = ({navigation}) => {
return(
<View>
<Button title={"Go Test"} onPress={() => navigation.navigate('Test')}/>
</View>
);
}
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="Test" component={Test} />
</Stack.Navigator>
</NavigationContainer>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
export default App
Output Output
Start: false
Flag changed! false
Flag changed! true
Exiting: false
Print flag false
Thanks in advance!提前致谢!
If you want to have access to the new value of changeFlag
in useEffect
you need to put it in the []
at the end of the useEffect
, by doing this you're saying the useEffect
to keep track of the updated value如果您想在changeFlag
中访问 c useEffect
的新值,则需要将其放在useEffect
末尾的[]
中,这样做就是说useEffect
来跟踪更新的值
useEffect(() => {
console.log(`Start: ${changeFlag}`);
return function cleanup () {
console.log(`Exiting: ${changeFlag}`);
updateStore();
};
}, [changeFlag]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.