I'm creating a react-native app using react-navigation 5.
Let's say I have a screen component like this:
import {View, Text} from 'react-native';
function TextScreen({navigation}) {
const [text, setText] = useState(null);
useEffect(() => {
setText('Some text.');
navigation.addListener('focus', () => {
console.log('focus');
console.log(text); // this is always null :/
});
}, []);
return (
<View>
<Text>{text || 'No text'}</Text>
</View>
);
}
I have no idea why every console.log(text)
displays null
value on every focus. I expect text to be null
only in the first focus but it happens all the time.
But when I changed this component into class component, everything worked as expected:
import {View, Text} from 'react-native';
class TextScreen extends React.Component {
state = {
text: null
}
componentDidMount() {
this.setState({text: 'Some text'});
this.props.navigation.addListener('focus', () => {
console.log('focus');
console.log(this.state.text); // this is null only in the first focus
});
}
render() {
return (
<View>
<Text>{this.state.text || 'No text'}</Text>
</View>
);
}
}
Is there something I'm doing wrong in the first version?