![](/img/trans.png)
[英]React: Cannot read property 'map' of undefined with conditional statement
[英]React cannot read property of undefined when accessing from e.g. IF statement
Redux將我的應用程序狀態變為props,並且在API請求完成后,我想訪問某些props的屬性。 但是,收到上述消息后,我的頁面無法呈現。
開始GET請求:
componentWillMount() {
this.props.renderRoles(this.props.params.roleID);
};
渲染用戶確實可以:
renderUsers(){
return this.props.roleDetails.userList.map((user)=>{
return(
<li className='list-group-item eventUserList' background-color="#f2f2f2" key={user._id}>
{user.userName}
</li>
);
});
};
render() {
const { handleSubmit, fields: {} } = this.props;
這是問題所在。 不知何故,如果我尋找它們的屬性,this.props的屬性將變得不確定:
if (this.props.roleDetails.roleName){
return (
如果我只尋找this.props.roleDetails,它確實可以工作,但在尋找其屬性時卻行不通:
if (this.props.roleDetails){
return (
<div className='container-fluid'>
<form>
<div className="roleDetails">
<div className="roleName">
{this.props.roleDetails.roleName}
</div>
</div>
<div className="roleUsers">
<div className="userDetails">
<h4 className="listOfUsers">Role Owner :</h4>
<ul>
{this.renderUsers()}
</ul>
</div>
</div>
<div>
<div className="submitRole" onClick={this.submitForRole.bind(this)}>Apply</div>
</div>
</form>
</div>
);
}else {
return (
<div>
</div>
);
}
}
}
function mapStateToProps(state) {
return{
roleDetails: state.api.roleDetails,
refreshedRole: state.api.refreshedRole
}
}
export default reduxForm({
form: 'roleView',
fields: []
}, mapStateToProps, actions)(roleView);
其他類似的問題與功能有關,但在我的情況下是關於訪問道具的,因此.bind(this)不起作用。
if (this.props.roleDetails.roleName)
看起來像roleDetails
undefined
,因為您可以通過請求獲取數據,因此,如果您嘗試訪問其屬性roleName
,則會收到錯誤消息。
if (this.props.roleDetails && this.props.roleDetails.roleName)
不應引發錯誤。
在componentWillMount
獲取數據不是好主意,而是使用componentDidMount
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.