我正在我的操作中的异步调用中返回一个数组,然后将其传递到还原器,最后回到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:
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
功能也应返回某些内容,您应该使用映射的数组来做某事。即feeds.map
的结果