Alex Smirnov
Alex Smirnov

Reputation: 31

Why the mapStateToProps returns "undefined" in React/Redux

Why the function mapStateToProps returns "undefined" or empty object in React/Redux.

My code:

import React from 'react'
import {connect} from "react-redux";

export const ArticleComponent = ({props}) => (
<div>
    <h1>Hello {console.log(props)}</h1>
</div>
);

const mapStateToProps = (state) => {
  return {
    text: '11111'
  }
};

export default connect(mapStateToProps)(ArticleComponent);

Upvotes: 0

Views: 904

Answers (4)

Dyo
Dyo

Reputation: 4464

You made multiple mistakes in your code :


  • You export your initial component AND you make a default export to the connected component.

Remove the export on the initial component and import your default export with :

import ArticleComponent from "./ArticleComponent" // No curly braces{ } to import the default;

  • You're accessing props.props (which is undefined) by doing const ArticleComponent = ({props}) =>

Remove curly braces to access all props passed to this component : const ArticleComponent = (props) =>(or use curly braces to get only the {text} prop)


  • You log the props in console (this is not an error but I don't think this is intentional)

Display the state like this : <h1>Hello {props.text}</h1>


Here's the full code :

import React from 'react'
import {connect} from "react-redux";

const ArticleComponent = ({text}) => ( // or (props)
<div>
    <h1>Hello {text}</h1> // or {props.text}
</div>
);

const mapStateToProps = (state) => {
  return {
    text: '11111'
  }
};

export default connect(mapStateToProps)(ArticleComponent);

Upvotes: 1

Intellidroid
Intellidroid

Reputation: 1055

you can't use a const like this it will never work. And why are you returning a text value (is this just to test it)?

import React, {Component} from 'react'
import {connect} from "react-redux";

class ArticleComponent extends Component {
render() {
const {text} = this.props
return (
<div>
    <h1>Hello {console.log(text)}</h1>
</div>
)
}
}


const mapStateToProps = (state) => {
  return {
    text: '11111'
  }
};

ArticleComponent = connect(mapStateToProps)(ArticleComponent);

export default  ArticleComponent;

Upvotes: 0

Burak Gavas
Burak Gavas

Reputation: 1354

I didn't understand why you want to extract props from props.

Instead of

export const ArticleComponent = ({props})

Write

const ArticleComponent = (props)

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281626

In order for the props to be received properly you need to use the connected instance of the component. Import it as a default import since connected component is the default export.

import ArticleComponent from 'path/to/ArticleComponent'

Upvotes: 0

Related Questions