Javascript 访问对象内部数组的长度会得到';TypeError:无法读取属性';长度';未定义的';
我遇到一个错误Javascript 访问对象内部数组的长度会得到';TypeError:无法读取属性';长度';未定义的';,javascript,reactjs,api,redux,square-bracket,Javascript,Reactjs,Api,Redux,Square Bracket,我遇到一个错误TypeError:当试图访问从MapStateTops获取的对象内部的数组长度时,无法读取未定义的属性“length”。。。在我的actions文件夹中,我创建了一个函数getuserdata,该函数进行api调用并成功返回一个对象。在我的组件中,我在componentdidMount中调用this.props.getuserdata,并使用getuserdata映射StateTrops currentUser状态。。。虽然tt返回一个对象,但它不允许我访问其中一个属性数组的长度
TypeError:当试图访问从MapStateTops获取的对象内部的数组长度时,无法读取未定义的属性“length”
。。。在我的actions文件夹中,我创建了一个函数getuserdata,该函数进行api调用并成功返回一个对象。在我的组件中,我在componentdidMount中调用this.props.getuserdata,并使用getuserdata映射StateTrops currentUser状态。。。虽然tt返回一个对象,但它不允许我访问其中一个属性数组的长度。。。。
我的mapstatetoprops写道:
currentUser:state.currentUser.getUserData
组件文件夹
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);
如果
this.props.currentUser
应该通过this.props.getUserData()
获得,那么问题可能是在使用render
方法时API调用没有完成。this.props.getUserData是否通过状态更改以任何方式“修改”this.props.currentUser?因为它看起来像是作为函数而不是数组传递currentUser。console logging current user为您提供了什么?我得到了一个具有current users属性的对象的控制台。您没有发布任何有用的代码,例如出现.length
的代码或api发送的数据结构。但是您可以通过将console.log(apiarse)
然后console.log(apiarse.theArray)很容易地调试它代码>等等。。。然后你会看到你的错误。明白了。如果myStocks属性不在该列表中,那么它不会被API返回,或者如果请求是AJAX请求,那么你可能在初始化之前访问了该属性。我猜是的。我访问MapStateTops中的getUserdata api数据。currentUser:state.currentUser.getUserData,
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',
});
}
}