[英]I'm having trouble looping through an array
我正在使用MyJSON为我的数据创建存储,并且无法遍历该存储
我已经尝试过.map()、. forEach,但是我无法终生在对象数组上进行映射。
TypeError: Cannot read property 'map' of undefined
JSON存储看起来像这样
const Leaderboard = (props) => {
useEffect(() => {
props.fetchScores();
},[]);
const renderList = () => {
props.scores.map(item => {
return <LeaderboardItem name={item.name} data={item.date} />
})
}
return (
<div className="leaderboard">
<h1 className='leaderboard__header'> Leaderboard</h1>
{renderList()}
</div>
);
};
const mapStateToProps = (state) => {
return {
scores: state.scores
};
};
export default connect(mapStateToProps, { fetchScores })(Leaderboard);
我能够获取数据,并将其添加到我的减速器中。 当我console.log我的道具我得到这个
(5) [{…}, {…}, {…}, {…}, {…}]
0: {name: "ryan", score: 3, date: 1564079441826, id: 1}
1: {name: "ryan", score: 0, date: 1564080251976, id: 2}
2: {name: "ryan", score: 4, date: 1564080621616, id: 3}
3: {name: "ryan", score: 1, date: 1564088666800, id: 4}
4: {name: "ryan", score: 8, date: 1564088919233, id: 5}
length: 5
__proto__: Array(0)
我不应该能够在数组上映射并返回每个对象吗?
10 | },[]);
11 |
12 | const renderList = () => {
> 13 | props.scores.map(item => console.log(item))
| ^ 14 | }
15 |
16 | return (
export default (state = {}, action) => {
switch(action.type) {
case FETCH_SCORES:
return { ...state, ...action.payload }
default:
return state;
};
};
图片 :
渲染项目列表, 您需要在地图中实际返回JSX
const renderList = () => {
props.scores.map(item => <div key={item.id}>{item.name}</div>)
}
由于scores
是不确定的,因此您需要确保正确引用事物。
scores
是combineReducers
定义的关键吗? 亦称诸如combineReducers({scores: scoresReducer})
更新您的reducer以始终存储要存储的内容。 不要更改数据类型
const defaultState = {
scores: []
}
export default (state = defaultState, action) => {
switch(action.type) {
case FETCH_SCORES:
return { ...state, scores: ...action.payload }
default:
return state;
};
}
假设action.payload
是一个分数数组,如果不是,则相应地进行调整
map
创建另一个数组作为原始数组的转换。 您只需在console.log
遍历每个项目,这将用于forEach
而不是map
。
console.log
的返回值是undefined
,在呈现[undefined, undefined, ...]
数组时可能会导致问题
您可以考虑一下:
props.scores && props.scores.map(item => {
return <LeaderboardItem name={item.name} data={item.date} />
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.