Andrew
Andrew

Reputation: 7

mapping redux state to props not working

trying for first time redux on a react-native app and i have this problem...

after i connect the component , and pass a mapStateToProps call, inside the function i can log the state perfectly fine. But, when i use this prop in the component its undefined. I am using the redux state in other component just fine...

Thks!

import React from 'react';
import { Container, Content, Button, 
Text,Card,CardItem,Body,Icon,Header,Left,Right,Title  } from 'native-base';

import { connect } from 'react-redux';

class HomeScreen extends React.Component {

    static navigationOptions = {
        header: null
    };

    tryLogout(){
         console.log(this.props.isLogged);
         // UNDEFINED HERE
   }

   render() { 

     return (
       <Container>
         <Header>
           <Left></Left>
           <Body>
             <Title>Menu</Title>
           </Body>
           <Right>
             <Button transparent onPress={this.tryLogout}>
               <Icon name='menu' />
             </Button>
           </Right>
         </Header>
         <Content padder>                  
         </Content>
       </Container>
     );
   }
 }

 const mapStateToProps = state => {
   console.log(state.isLogged);
   // I GET DATA HERE
   return {
       isLogged: state.isLogged
   }
 }

 export default connect(mapStateToProps,{})(HomeScreen);

Upvotes: 0

Views: 920

Answers (2)

Rodrigo Ferreira
Rodrigo Ferreira

Reputation: 1091

The problem is that when you are calling this.tryLogout, the this keyword is dynamically binded to the event instead of the component itself, so the event doesn't have the prop that you are looking for.

You can take different approaches on how to solve this:

Using named arrow functions

tryLogout = () => console.log(this.props)
...
onPress={this.tryLogout}

Using the bind method

onPress={this.tryLogout.bind(this)}

Using inline arrow functions

onPress={() => this.tryLogout()}.

You can take a look to the different techniques in the docs: How do I bind a function to a component instance?

Upvotes: 1

reisdev
reisdev

Reputation: 3383

You're receiving this error because your tryLogout() isn't binded to your component. So, the this reference isn't of your component. Change the declaration to this:

tryLogout = () => {
     console.log(this.props.isLogged);
}

The () => {} , known as arrow function, does the bind for you.

TIP:

If you build a method for your component that needs to access any prop or state, you'll need to bind the function to the component class. When you declare the method as I did above, you're binding it. So, your method will have the possibility to access any prop or state of your component.

Upvotes: 0

Related Questions