繁体   English   中英

访问 object 中的数组长度给我“TypeError:无法读取未定义的属性“长度”

[英]accessing length of an array inside an object gives me 'TypeError: Cannot read property 'length' of undefined'

我收到一个错误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写道:

当前用户: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);

动作文件夹:


    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',
    });
  }
}

如果this.props.currentUser应该通过this.props.getUserData()获得,则问题可能是您的 API 调用未完成,而反应使用render方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM