【发布时间】:2019-12-04 05:51:53
【问题描述】:
我正在使用 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;
};
};
图片:
【问题讨论】:
-
你是如何连接组件的?您没有正确传递数组。您也没有在
renderList中返回 jsx -
请添加更多代码。该错误表明
props.scores不包含任何内容 -
更新帖子以显示我的组件!当我在 mapStateToProps 中使用 console.log(state.scores) 时,它显示它包含对象数组
-
我还可以通过 redux-dev 工具看到我的分数缩减器返回相同的分数数组,其中包含对象
-
请发布您的减速器代码。状态是否类似于
{ scores: [] }?您需要像state.scores.scores一样连接它。state.scores是整个分数缩减器,如果您的列表是该对象上的键,您需要引用它。既然它说的是未定义,请确保scores是combineReducers中的键