Reputation: 5053
I am using React in my application. I am using connect to access the store, Briefly I have this code:
class MyComponent extends Component{
constructor(props){
super(props)
}
render(){
let components = this.props.components;
if(components.indexOf("SomeString")){
//some stuffs
}
return (
<SomeElement/>
)
}
}
const mapStateToProps = state => {
return {
components: state.someReducer.components
}
}
export default connect(mapStateToProps)(MyComponent)
Components is an array of strings, if I print with console.log(this.props.components)
inside the render function, the I am able to see the array in the browser console. However, if I try to find a value inside that array using indexOf
then I get this error:
TypeError: components is undefined
So, What am I missing? I tried many things without result
Upvotes: 0
Views: 486
Reputation: 3905
You need to check for the this.props.components
like so:
render(){
if(this.props.components) {
let components = this.props.components;
if(components.indexOf("SomeString")){
//some stuffs
}
return (
<SomeElement/>
)
} else {
return(<div>Loading...</div>)
}
}
Upvotes: 0
Reputation: 125
At first cycle, this.props.components
is undefined. You can bypass it using
render(){
if(this.props.components) {
let components = this.props.components;
if(components!=null || components!=undefined){ //this will check if components is null or undefined
if(components.indexOf("SomeString")){
//some stuffs
}}
return (
<SomeElement/>
)
}
Upvotes: 2