[英]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.