簡體   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