代码之家  ›  专栏  ›  技术社区  ›  Kamil Kamili

访问异步调用返回的数组项时出现问题

  •  1
  • Kamil Kamili  · 技术社区  · 8 年前

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

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

    Reducer:

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

    现在在我的 mapStateToProps 我从dispatch接收到初始的空数组,然后是填充的数组。

    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 回复  |  直到 8 年前
        1
  •  1
  •   dashton    8 年前

    从你的日志来看 feedState.feeds 是一个数组。所以 feed.feedID 行不通。 feed[0].feedID 会有用的。

    也是你的 .map 函数应该返回一些内容,您应该对映射的数组执行一些操作。i、 e.结果 feeds.map

    推荐文章