Reputation: 31
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
Reputation: 4464
You made multiple mistakes in your code :
Remove the export on the initial component and import your default export with :
import ArticleComponent from "./ArticleComponent" // No curly braces{ } to import the default;
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)
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
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
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
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