我正在尝试访问传递给组件的React JS prop中的嵌套对象。
当我在控制台中记录它时, this.props.object
正常工作,但当我尝试访问a
时,我收到一条错误消息,指出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
按预期工作,但当我尝试访问venue.photo.source
时,它会给我上述错误。
我是新手做出反应,这可能是我失踪的一个简单原因。
答案 0 :(得分:0)
如果object
支柱来自某些异步操作,则可能是您在定义object.a
之前尝试记录object
。
检查它的定义是否可以解决您的问题。
this.props.object && console.log(this.props.object.a)