I've set up a Redux store in my RN application. The store works fine, if I use store.getState() I can see all the data inside my store. However, if I try to retrieve it from connect, it doesn't work. I think it's due to the fact that I'm using a functional component and not a class.
App.js (also functional component)
return (
<Provider store={store}>
<NavigationContainer>
<Stack.Navigator >
<Stack.Screen name="Home"
options={({ navigation, route }) => ({
headerTitle: 'Hi, {nome}',
headerRight:() => (
<Pressable onPress={() => updateLogin(false)}>
<Text>
Log Out
</Text>
</Pressable>
),
headerBackVisible: false
})}
component={HomeScreen}
/>
<Stack.Screen name="Calendar" component={CalendarScreen} />
<Stack.Screen name="SignUp" component={SignUpMainScreen} options={{headerShown:false}}/>
<Stack.Screen name="Login" component={LoginScreen} options={{headerShown:false}}/>
<Stack.Screen name="SignUpEmail" component={SignUpEmailScreen} options={{headerShown:false}}/>
</Stack.Navigator>
</NavigationContainer>
</Provider>
Homescreen.js
//Other imports
import * as React from 'react';
import {connect} from 'react-redux'
import store from '../api/redux/store';
import {updateLogin} from '../api/redux/actions'
function HomeScreen({ navigation}) {
return (
<View style={styles.container}>
<Text>{this.props.user.name}</Text>
</View>
);
}
const styles = StyleSheet.create({...})
const mapStateToProps = state => ({
name: state.user.name,
})
export default connect(mapStateToProps)(HomeScreen)
CodePudding user response:
Looks like I found the answer myself. You need to pass as props to the screen the props that you define inside mapStateToProps()
.
In this case,
name: state.user.name
goes inside HomeScreen({navigation, name})
.
you can find it here even though the example was not super clear.
CodePudding user response:
I always recommend using hooks in functional components since its way easier to read and understand.
In this case it would be:
import {useSelector} from 'react-redux'
const name = useSelector(state => state.user.name)