Bosco Tsin
Bosco Tsin

Reputation: 183

React: Getting Content from State Array Element

I was experimenting with React State where one of the states is an array and I am trying to access one of the individual array elements. I found the line below problematic:

const Character = this.state.Characters[0];

If I use the above line in the code below, React would return error, however if I use:

const Character = somedefinedarray[0];

The below codes would work, but I could not see the difference for the two lines above at all. Can anyone enlighten me somehow? Might it be something related to "this" or state array access or so???

class Ch extends Component {
    constructor(props) {
        super(props);
        this.state = {
            Characters: []
        }
    }
    componentDidMount() {
        this.setState({Characters: somedefinedarray});
    }
    render() {
        const Character = this.state.Characters[0];
        return (
            <p>{Character.somestate}</p>
        )
    }
}

Upvotes: 0

Views: 477

Answers (1)

Nisanth Reddy
Nisanth Reddy

Reputation: 6430

During your first render, your default state is Characters: [].

So, when you access Character = this.state.Characters[0];, Character will be undefined because your state array is empty.

Then, you try to use Character.somestate which will result in an error saying, cannot read property somestate of undefined.

Upvotes: 1

Related Questions