【问题标题】:issue accessing Array Items returned from Async call访问从异步调用返回的数组项的问题
【发布时间】:2018-05-24 03:09:25
【问题描述】:

我正在从我的操作中的异步调用返回一个数组,然后将其传递给减速器,最后返回到 React。但是,每当我尝试访问其中的元素时,都会出现错误。我的第一个猜测是我的异步调用可能是错误的,所以我到处都是console.log。但一切似乎都很好,除非我尝试映射数组。

以下是步骤顺序:

Dispatch Action:

.then(feeds => {
            console.log('Sending data to dispatch');
            console.log(`Testing this function -> ${JSON.stringify(feeds)}`);
            dispatch({
                type: 'RETRIEVE_FEEDS',
                payload: feeds,
            });

最初 feeds 是我的 reducer 中的一个空数组,然后用这个数组填充。

Reducer:

 case 'RETRIEVE_FEEDS': {
            return { ...state, feeds: action.payload };
        }

现在在我的mapStateToProps 中,我收到了初始的空数组,然后收到了来自调度的填充数组。

const mapStateToProps = ({ feedState }) => {
    const { feeds } = feedState;
    console.log(`FeedState -> ${JSON.stringify(feedState.feeds)}`);
    console.log(`Is Array -> ${Array.isArray(feedState.feeds)}`);
    console.log(`Going to map through the array`);
    feedState.feeds.map(feed =>{
        console.log(`Feed -> ${JSON.stringify(feed)}`)
        console.log(`Feed ID -> ${feed.feedID}`)
    });
    return { feeds };
};

我唯一的问题是,每当我尝试从数组中获取某些内容时,它都会变得未定义。

这些是我的日志:

FeedState -> []

Is Array -> true

Going to map through the array

Sending data to dispatch

Testing this function -> [[{"feedID":"57dfnQuwUghupbRB7EEB","uploadedBy":"8Vmr0ZnVDPfgkCqSBWHXjaVEDYH3","videoURL":"","datePosted":"2017-12-08T14:24:37.323Z","tags":[],"isLike":false,"likes":{"countLikes":0}}],[{"feedID":"reYEcurssCV32WyQgOYp","uploadedBy":"8Vmr0ZnVDPfgkCqSBWHXjaVEDYH3","videoURL":"","datePosted":"2017-12-08T14:46:13.655Z","tags":[],"isLike":false,"likes":{"countLikes":0}}]]

FeedState -> [[{"feedID":"57dfnQuwUghupbRB7EEB","uploadedBy":"8Vmr0ZnVDPfgkCqSBWHXjaVEDYH3","videoURL":"","datePosted":"2017-12-08T14:24:37.323Z","tags":[],"isLike":false,"likes":{"countLikes":0}}],[{"feedID":"reYEcurssCV32WyQgOYp","uploadedBy":"8Vmr0ZnVDPfgkCqSBWHXjaVEDYH3","videoURL":"","datePosted":"2017-12-08T14:46:13.655Z","tags":[],"isLike":false,"likes":{"countLikes":0}}]]

Is Array -> true

Going to map through the array

Feed -> [{"feedID":"57dfnQuwUghupbRB7EEB","uploadedBy":"8Vmr0ZnVDPfgkCqSBWHXjaVEDYH3","videoURL":"","datePosted":"2017-12-08T14:24:37.323Z","tags":[],"isLike":false,"likes":{"countLikes":0}}]


Feed ID -> undefined

【问题讨论】:

  • 您是如何以及在哪里尝试从数组中获取内容的?
  • 我只是在 mapStateToProps 函数中映射数组
  • 你的map函数什么都不做,你为什么不做一个foreach呢?
  • 你的最终console.log不应该是“console.log(Feed ID -> ${JSON.stringify(feed).feedId})”吗?
  • 在 mapStateToProps 函数中尝试使用 return 关键字返回一些东西

标签: javascript arrays react-native promise redux-thunk


【解决方案1】:

从您的日志看来,feedState.feeds 中的每个项目都是一个数组。所以feed.feedID 不起作用。 feed[0].feedID 会起作用。

你的.map 函数也应该返回一些东西,你应该对你的映射数组做一些事情。即feeds.map的结果

【讨论】:

    猜你喜欢
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    相关资源
    最近更新 更多