I am trying to access a nested object in a React JS prop passed to a component.
this.props.object
works when I log it in the console but I get an error saying that a
is undefined when I try to access this.props.object.a
.
Cannot read property 'source' of undefined
at VenueDetails (VenueDetails.js:8)
at ReactCompositeComponent.js:306
at measureLifeCyclePerf (ReactCompositeComponent.js:75)
at ReactCompositeComponentWrapper._constructComponentWithoutOwner (ReactCompositeComponent.js:305)
at ReactCompositeComponentWrapper._constructComponent (ReactCompositeComponent.js:280)
at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:188)
at Object.mountComponent (ReactReconciler.js:46)
at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:371)
at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
at Object.mountComponent (ReactReconciler.js:46)
VenueDetailsView.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { VenueDetails } from '../presentation';
import { fetchVenue } from '../../redux/actions/venues';
class VenueDetailsView extends Component {
constructor(props) {
super(props);
this.state = {
venue: {},
};
}
componentDidMount() {
this.props.fetchVenue(this.props.match.params.id);
}
render() {
return (
<VenueDetails venue={this.props.selectedVenue}/>
);
}
}
const mapStateToProps = (state) => ({
selectedVenue: state.selectedVenue,
});
export default connect(mapStateToProps, { fetchVenue })(VenueDetailsView);
VenueDetails.js
import React, { PropTypes } from 'react';
import { Card, CardMedia, CardTitle, CardText, CardActions, FlatButton } from 'material-ui';
const VenueDetails = ({ venue }) => {
return (
<Card>
<CardMedia overlay={<CardTitle title={venue.name}/>}>
<img src={venue.photo.source}/>
</CardMedia>
<CardText>
</CardText>
<CardActions>
<FlatButton label="Action1" />
<FlatButton label="Action2" />
</CardActions>
</Card>
);
};
VenueDetails.propTypes = {
venue: PropTypes.object.isRequired,
};
export default VenueDetails;
venue.name
works as expected but when I try to access venue.photo.source
it gives me the above error.
I am new to react and there is probably a simple reason that I am missing.
If the object
prop is from some async action, it may be that you're trying to log object.a
before object
is defined.
Checking that it's defined may solve your problem.
this.props.object && console.log(this.props.object.a)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.