Greg M
Greg M

Reputation: 65

Redux & React Native component connect: this.props is undefined

I am trying to access the name field as defined in the initial state of my reducer. At the moment, this.props is returning undefined.

My reducer:

import { combineReducers } from 'redux';

const INITIAL_STATE = {
    name: "Test"
}

const userReducer = (state = INITIAL_STATE, action) => {
    switch (action.type) {
      default:
        return state
    }
};

export default combineReducers({
  user: userReducer,
});

The component being rendered (this logs "Props: undefined"):

const AddName = ({ navigation }) => {

    ...

    console.log("Props: ", this.props)

    return (
        <>
        ...
        </>
    )
}

mapStateToProps = (state) => {
    return{
      user : state.user
    };
}

export default connect(mapStateToProps, null)(AddName)

Creating the redux store and provider:

...
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducer from './src/reducers/userReducer';

const store = createStore(reducer)

const AppContainer = () => 
    <Provider store={store} >
        <App />
    </Provider>


AppRegistry.registerComponent(appName, () => AppContainer);

Upvotes: 1

Views: 254

Answers (3)

Shubham Sharma
Shubham Sharma

Reputation: 499

You should use class components instead of the function component. Read more about that.

https://codeburst.io/react-js-understanding-functional-class-components-e65d723e909

Upvotes: 0

Gaurav Roy
Gaurav Roy

Reputation: 12195

You are using a functional component and this keyword doesnt apply to functional components, rather it applies it to class Components.

Change your component as below :

class AddName extends React.Component {

    ...

    console.log("Props: ", this.props)

    render(){
    return (
        <>
        ...
        </>
    )

     }

}

mapStateToProps = (state) => {
    return{
      user : state.user
    };
}

export default connect(mapStateToProps, null)(AddName)

hopeit helps. feel free for doubts

Upvotes: 1

Shayan Moghadam
Shayan Moghadam

Reputation: 2050

You are using a function Component so you should use props in this way :

const AddName = (props) => {

...

console.log("Props: ", props)

return (
    <>
    ...
    </>
 ) 
}

Upvotes: 0

Related Questions