Salman Salman - 1 month ago 16
React JSX Question

react: Initial state value is undefined

I am trying to set an initial value to my states. I used

constructor
to populate some values to my state.

import React,{Component} from 'react';

export default class RandomWords extends Component{
constructor(props){
super(props);
const str="Italy quake: Norcia tremor destroys ancient buildings";
const words = str.split(" ");
this.state= {
activeWord:0,
activeLetter:0,
words:words
};
}
render(){
console.log("words are:"+this.props.words);
return(<div>
{ this.props.words }
</div>)
}
}


and then i used
mapStateToProps
to connect
state
to
props
. Here is the container:

import RandomWords from '../components/RandomWords';
import {connect} from 'react-redux';

function mapStateToProps(state){

return ({words:state.words,
activeLetter:state.activeLetter,
activeWord:state.activeWord});
}

export default connect(mapStateToProps)(RandomWords);


As you see, in my
render()
function, I have
console.log("words are:"+this.props.Words);
and i expect to see the splitted words.
But in console there is only
undefined

Answer

mapStateToProps is used to map the Redux state from your store to the component's props.

However, you are initializing the component state. Two different concepts. You can access the component state via this.state:

 render(){
     console.log("words are:" + this.state.words);
     return(<div>
         {this.state.words}
     </div>)
  }
Comments