Reputation: 61
import React, { Component } from 'react';
class newsList extends React.Component {
render(){
return(
<div>
{JSON.stringify(this.props.arr)}
</div>
)
}
}
export default newsList;
In the above code, arr
is an object coming from another component. I can display the data using JSON.stringify(this.props.arr.result)
. But as soon as I change it with JSON.stringify(this.props.arr.result.id)
, I am getting an error says TypeError: this.props.arr.result is undefined
. I cannot understand what I am doing wrong here?
Upvotes: 0
Views: 189
Reputation: 719
Try out this code instead:
class NewsList extends React.Component {
constructor(props) {
super(props);
this.props = props;
}
render() {
return <div>{this.props.arr}</div>;
}
}
A React.Component
's constructor
always receives props
as it's first parameter.
Upvotes: 0
Reputation: 316
Is this.props.arr
Array?
If it is, the render function should be
render(){
var ids = this.props.arr.map(e=>(<div>e.result.id</div>))
return(
<div>
{ids}
</div>
)
}
Upvotes: 0
Reputation: 7555
I'm almost positive that, at some point in time, your this.props.arr
is undefined
, but then eventually gets assigned a value. Your initial render will receive a null
or undefined
, but if you try and go one step further into a key that doesn't exist, you will throw that error. You can use a boolean to control what gets initially rendered.
Instead of this line of code:
{JSON.stringify(this.props.arr)}
try this:
{this.props.arr ? JSON.stringify(this.props.arr) : null}
edit: is your issue with this.props.arr.result.id
? If so, use this instead
{this.props.arr.result ? JSON.stringify(this.props.arr.result.id) : null}
Upvotes: 1