0

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

3
  • did you define an initial state for the someReducer reducer? Commented Aug 30, 2017 at 2:16
  • @elas yes, indeed when I print the array in the console I see the values and they're correct Commented Aug 30, 2017 at 2:19
  • I can be sure with the error that components is getting undefined one reason or another, The problem doesn't lie in the snippet you provided.. maybe its there somewhere higher up. As the others already said, provide a check before rendering the result Commented Aug 30, 2017 at 6:15

2 Answers 2

2

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/>
          )
    }
Sign up to request clarification or add additional context in comments.

3 Comments

ok, but now my question is: why is the array printed in the console pretty well? and it's at first cycle
Where did you put the console.log? .render() is the first part to be calles in a react lifecycle.
I out it inside render
0

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>)
      }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.