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

issue accessing Array Items returned from Async call

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

最初 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

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

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

的结果