[英]accessing length of an array inside an object gives me 'TypeError: Cannot read property 'length' of undefined'
I get an error TypeError: Cannot read property 'length' of undefined
when trying to access length of an array inside of an object that I get from mapstatetoprops... In my actions folder, i created a function getuserdata that makes an api call and successfully returns an object.我收到一个错误
TypeError: Cannot read property 'length' of undefined
当试图访问我从 mapstatetoprops 获得的 object 中的数组长度时...成功返回 object。 in my component i call this.props.getuserdata in componentdidMount, and i mapstatetoprops currentUser state with getUserdata... although tt returns an object, it does not allow me to access the length of one of the properties arrays.... my mapstatetoprops writes: in my component i call this.props.getuserdata in componentdidMount, and i mapstatetoprops currentUser state with getUserdata... although tt returns an object, it does not allow me to access the length of one of the properties arrays.... my mapstatetoprops写道:
currentUser: state.currentUser.getUserData当前用户:state.currentUser.getUserData
components folder组件文件夹
class Users extends Component {
componentDidMount() {
this.props.getUserData();
this.props.getOtherUsers();
}
render() {
console.log(this.props.currentUser.myStocks.length,'current user')
return (
<Container>
</Container>
)
}
};
function mapStateToProps(state) {
return {
currentUser: state.currentUser.getUserData,
filteredUsers: state.filteredUsers.getOtherUsers,
getUsersError: state.users.getUsersError
};
}
export default compose(
connect(mapStateToProps, { getUserData, getOtherUsers }),
requireAuth
)(Users);
actions folder:动作文件夹:
export const getUserData = () => async (dispatch) => {
try {
const { data } = await axios.get('/api/user/profile', {
headers: { authorization: localStorage.getItem('token') },
});
// console.log(data.myStocks[0],'inform')
dispatch({ type: GET_USER_DATA, payload: data });
} catch (e) {
dispatch({
type: GET_USER_DATA_ERROR,
serverError: e,
clientError: 'Something went wrong please refresh try again',
});
}
}
If this.props.currentUser
is supposed to be obtained by this.props.getUserData()
maybe the problem is that you API call is not finish while react use the render
method.如果
this.props.currentUser
应该通过this.props.getUserData()
获得,则问题可能是您的 API 调用未完成,而反应使用render
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.