我有这个数组的数据,这些数组经过循环并以uploads
的形式以Redux状态添加到映射中,以便在组件中进行访问。我的组件只接受一个数组,因为它是dataSource
,因此需要将地图的值转换为数组。我收到一个错误。记录函数generateUploadsMap
时,我不确定。
TypeError: Cannot read property 'values' of undefined
Home.render
./components/home/components/Home.jsx:24
21 | render() {
22 | const { uploads } = this.props;
23 | // convert uploads values to an array
> 24 | const values = [...uploads.values()];
| ^ 25 |
26 | return (
27 | <div style={CARD_CONTAINER}>
reducers.js
import { UPDATE_REACTION, REQUEST_UPLOAD_LIST } from './actionTypes';
import { USER_UPLOADS } from './constants';
const INITIAL_STATE = {
uploads: new Map(),
};
function generateUploadsMap() {
const setOfUserUploads = new Map();
USER_UPLOADS.forEach(userUpload => {
const { _id } = userUpload;
setOfUserUploads.set(_id, userUpload);
});
}
export default (state = { ...INITIAL_STATE }, action) => {
switch (action.type) {
case REQUEST_UPLOAD_LIST: {
const { payload } = action;
return {
...state,
uploads: generateUploadsMap(payload),
};
}
default:
return state;
}
};
Home.js
import React from 'react';
import { Avatar, Card, Icon, List } from 'antd';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { LIST_TEXTS, STYLES } from '../constants';
import * as actions from '../actions';
import { getUploads } from '../selectors';
const { AVATAR, CARD_CONTAINER, CARD_LIST, USER_LIST } = STYLES;
const { INNER, MORE, UPLOAD, VERTICAL } = LIST_TEXTS;
class Home extends React.Component {
componentDidMount() {
const { requestUploadList } = this.props.actions;
requestUploadList();
}
render() {
const { uploads } = this.props;
const values = [...uploads.values()];
return (
<div style={CARD_CONTAINER}>
<List
itemLayout={VERTICAL}
dataSource={values}
renderItem={item => (
<List.Item style={USER_LIST}>
<Card
cover={<img alt={UPLOAD} src={item.image} />}
extra={<Icon type={MORE} />}
hoverable
title={(
<a>
<Avatar src={item.image} style={AVATAR} />
{item.user}
</a>
)}
type={INNER}
style={CARD_LIST}
>
{item.story}
</Card>
</List.Item>
)}
/>
</div>
);
}
}
const mapStateToProps = state => ({
uploads: getUploads(state),
});
const mapDispatchToProps = dispatch => ({
actions: bindActionCreators(actions, dispatch),
});
export default connect(mapStateToProps, mapDispatchToProps)(Home);
答案 0 :(得分:0)
您没有从generateUploadsMap
函数返回任何内容:
function generateUploadsMap() {
const setOfUserUploads = new Map();
USER_UPLOADS.forEach(userUpload => {
const { _id } = userUpload;
setOfUserUploads.set(_id, userUpload);
});
return setOfUserUploads;
}
要使用普通对象代替Map
,通常建议将其存储在redux状态:
function generateUploadsMap() {
return USER_UPLOADS.reduce((uploadsMap, upload) => {
return { ...uploadsMap, [upload._id]: upload };
}, {});
}
render() {
const { uploads } = this.props;
const values = Object.values(uploads);
...
}