javascript - React Nested Object Gives Error - Stack Overflow

I have a ponent that works and will return data from State as long as it isn't nested.However, i

I have a ponent that works and will return data from State as long as it isn't nested. However, if I need to dig a little deeper within the object, I get an error: "TypeError: Cannot read property 'name' of undefined".

I'm positive that there is a value for it (checked Inspector and the variable does indeed have a value, that's how I knew what to put in code). Why does it work for a higher value, but not the lower value?

class Concert extends Component {

constructor(props) {
    super(props);

    this.state = ({
        concert:''
    })
}
ponentDidMount(){
    var concertid = `${REQ_URL}/${this.props.match.params.concertid}`;
    fetch(concertid, {
        method: 'GET'
    })
    .then(response => response.json())
    .then(json => {
        this.setState({
            concert:json
        })
    })


}
render() {
    return (
        <div>
            <Header />
            <div className="concert">
                <div className="venue">

                //THIS IS THE PART THAT RETURNS ERROR
                //this.state.concert.id returns a correct value
                //POSITIVE this.state.concert.artist.name DOES CONTAIN VALUE

                Venue: {this.state.concert.artist.name}
                </div>

            </div>
        </div>
        )
}

}

I have a ponent that works and will return data from State as long as it isn't nested. However, if I need to dig a little deeper within the object, I get an error: "TypeError: Cannot read property 'name' of undefined".

I'm positive that there is a value for it (checked Inspector and the variable does indeed have a value, that's how I knew what to put in code). Why does it work for a higher value, but not the lower value?

class Concert extends Component {

constructor(props) {
    super(props);

    this.state = ({
        concert:''
    })
}
ponentDidMount(){
    var concertid = `${REQ_URL}/${this.props.match.params.concertid}`;
    fetch(concertid, {
        method: 'GET'
    })
    .then(response => response.json())
    .then(json => {
        this.setState({
            concert:json
        })
    })


}
render() {
    return (
        <div>
            <Header />
            <div className="concert">
                <div className="venue">

                //THIS IS THE PART THAT RETURNS ERROR
                //this.state.concert.id returns a correct value
                //POSITIVE this.state.concert.artist.name DOES CONTAIN VALUE

                Venue: {this.state.concert.artist.name}
                </div>

            </div>
        </div>
        )
}

}

Share Improve this question asked Sep 19, 2017 at 21:17 homersheinekenhomersheineken 3336 silver badges15 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

When the ponent is rendered for the first time, the value of this.state.concert is '' (you set that value in the constructor) so if you are trying to access this.state.concert.artist.name you are actually trying to access undefined.name - and there is your error.

The value of this.state.concert is getting change only after the ponent was loaded - after the success callback of your fetch call is done, and only then that value will be available.

What you can do is check if you have a value before accessing it:

{this.state.concert && this.state.concert.artist &&
    <div>Venue: {this.state.concert.artist.name}</div>
}       

easy, api calls are asynchronous so this.state.concert.artist.name will be {"empty"} until you get the api response.

use this:

Venue: {this.state.concert && this.state.concert.artist && this.state.concert.artist.name}

The problem is it's trying to render before the data is there since the API call is asynchronous.

A nicer way to fix this is to extract the values using es6 object destructuring with defaults:

const {
  id,
  artist: {
    name
  } = {}
} = this.state.concert;

-

Venue: {name}

This way, if artist is not present you'll just get undefined instead of throwing an error

Also concert should be an object by default in the constructor:

this.state = {
    concert: {}
};

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744873658a4598416.html

相关推荐

  • javascript - React Nested Object Gives Error - Stack Overflow

    I have a ponent that works and will return data from State as long as it isn't nested.However, i

    1天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信