无法从阵列ES6获取信息

时间:2019-05-16 03:56:10

标签: javascript arrays reactjs ecmascript-6

我无法映射数组。首先我确实将一些对象压入了数组

const resultat = [];
resultat.push(object);

在那之后,当我控制台数组时,它正确地包含了对象

这是数组控制台的结果

[]
0: { user: {…}, name: "Test User 1", private: null, sharingspace: {…}}
1: { user: {…}, name: "FoodTest  ", private: null, sharingspace: {…}}
length: 2
__proto__: Array(0)

当我做地图时,它没有接收任何信息,我试图操纵resultat [0],但返回未定义。

这就像本文Javascript variable is an array of objects but can't access the elements的问题

我通过在axios上循环并填充对象来添加信息


//this is the part where I stored the data 
import { SET_SHARINGSPACES, SHARING_LOADING, CLEAR_SHARING } from "./types";
import axios from "axios";

export const setSharingSpaces = (org, user) => dispatch => {
  const orgName = org.value.substr(1);
  const groups = user.group.filter(group => group.includes(orgName));
  const resultat = [];
  dispatch(SharingLoading());
  groups.forEach(function(group, index) {
    let idparts = group.split("#");
    let aBox = "a" + orgName;
    axios
      .get("api/" + aBox + "/group/" + aBox + ":" + idparts[1])
      .then(res => resultat.push(res.data[0]));
  });
  dispatch(setSharing(resultat));
};
export const setSharing = res => {
  return {
    type: SET_SHARINGSPACES,
    payload: res
  };
};
// Graph loading
export const SharingLoading = () => {
  return {
    type: SHARING_LOADING
  };
};
// Graph loading
export const clearSharing = () => {
  return {
    type: CLEAR_SHARING
  };
};

在这里,我在加载数据时为组件充电

const { groups, loading } = this.props.sharingSpace;

    let SharingContent;
    if (groups == null || loading) {
      SharingContent = <h4>0 Spaces</h4>;
    } else {
      SharingContent = <SharingList groups={groups} />;
    }

,这里是使用数据的组件

class SharingList extends Component {
  render() {
    const { classes } = this.props;
    const { groups } = this.props.sharingSpace;
    console.log("group", groups);
    const names = groups.map(group => group.sharingspace.name);
    console.log(names);

    return (
      <List component="div" disablePadding>
        <ListItem button className={classes.nested}>
          <ListItemText inset primary="Space 1" />
        </ListItem>
      </List>
    );
  }
}
SharingList.propTypes = {
  classes: PropTypes.object.isRequired,
  sharingSpace: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
  auth: state.auth,
  sharingSpace: state.sharingSpace
});
export default connect(
  mapStateToProps,
  {}
)(withStyles(styles)(SharingList));

1 个答案:

答案 0 :(得分:0)

根据所提供的信息很难回答。

但是由于您提到的是axios,并且它与console.log“一起显示”,因此可能是种族效应。

这意味着您的数据尚不存在,因此[]时为console.log空数组,展开时为结果-Chrome正在做一些“魔术”操作来填充数组具有可用的最新数据,即使在console.log时为空。

因此,如果您直接console.log数组的第一个元素,它将尝试实际显示第一个元素(尚不存在),因此什么也不显示。

该图标上还带有一个小“ i”图标(您可以将其悬停在控制台中):

i icon