我正在开发一个 React 项目,在该项目中我试图访问一个对象中的键,该对象是使用索引的数组中的元素,但未定义。
问题似乎是我得到了一个对象数组作为 Prop ,索引也作为 Prop 。当我尝试使用 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);
最佳答案
尝试有条件渲染,因为它是在渲染内部调用的,可能是因为 props 的初始值没有这个值。
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>
);
}
}
关于javascript - react Prop : Unable to access key in object in array with index both passed with props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50808781/