访问从异步调用返回的数组项

时间:2017-12-10 12:00:46

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

我在我的动作中从异步调用返回一个数组,然后传递给reducer并最终返回到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,
            });

最初Feed在我的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

1 个答案:

答案 0 :(得分:1)

从您的日志中看,feedState.feeds中的每个项目都是一个数组。所以feed.feedID无法工作。 feed[0].feedID可行。

此外,您的.map函数应返回一些内容,您应该对映射的数组执行某些操作。即feeds.map

的结果