我正在研究一个React项目,在该项目中,我试图使用索引访问对象中的一个键,该对象是数组中的一个元素,但是未定义。
问题似乎是我将一组对象作为道具,索引也作为道具。当我尝试使用props中的索引访问数组中对象的id或publicid时,我收到错误。以下是我所获得的简化版本。
为什么会发生这种情况,我该如何解决?
console.log(this.props.images);
// [{id: 1, publicid: "1234" }, {id: 2, publicid: "5678"}]
console.log(this.props.imageIndex)
// 0
console.log(this.props.images[0].publicid)
// 1234
console.log(this.props.images[this.props.imageIndex])
// {id: 1, publicid: "1234" }
console.log(this.props.images[this.props.imageIndex].publicid)
// Cannot read property 'publicid' of undefined
**更新了更多代码**
import React, { Component } from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';
import * as actions from '../../actions';
class ImageBox extends Component {
handleClick() {
console.log('handleClose:');
}
renderImages() {
console.log(this.props.imageIndex);
// index logs okay
console.log(this.props.images[0]);
// shows correct object in the array
console.log(this.props.images[this.props.imageIndex]);
// again shows correct object in array
console.log(this.props.images[this.props.imageIndex].publicid);
// TypeError: Cannot read property 'publicid' of undefined
return (
<div onClick={this.handleClick.bind(this)}>
<div className="image-box-content">
</div>
</div>
);
}
}
render() {
return (
<div>
{this.renderImages()}
</div>
);
}
}
function mapStateToProps(state) {
return {
auth: state.auth,
successMessage: state.auth.success,
errorMessage: state.auth.error,
};
}
export default connect(mapStateToProps, actions)(ImageBox);
答案 0 :(得分:1)
有条件地尝试渲染,因为它在渲染中被调用,可能是因为道具的初始值没有这个值。
renderImages() {
console.log(this.props.imageIndex);
// index logs okay
console.log(this.props.images[0]);
// shows correct object in the array
console.log(this.props.images[this.props.imageIndex]);
// again shows correct object in array
if(this.props.images[this.props.imageIndex])
console.log(this.props.images[this.props.imageIndex].publicid);
// TypeError: Cannot read property 'publicid' of undefined
return (
<div onClick={this.handleClick.bind(this)}>
<div className="image-box-content">
</div>
</div>
);
}
}
答案 1 :(得分:0)
let images = [{id: 1, publicid: "1234" }, {id: 2, publicid: "5678"}];
let imageIndex = 0;
console.log(images);
// [{id: 1, publicid: "1234" }, {id: 2, publicid: "5678"}]
console.log(imageIndex)
// 0
console.log(images[0].publicid)
// 1234
console.log(images[imageIndex])
// {id: 1, publicid: "1234" }
console.log(images[imageIndex].publicid)
// Cannot read property 'publicid' of undefined
我仅从您的代码中删除了this.props
,以证明您的代码完全正常工作。您的console.log
之间必须有一些其他代码,您可能需要分享更多代码