繁体   English   中英

我在遍历数组时遇到麻烦

[英]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;
};

};

图片 :

终极版-dev的工具,此搜索

终极版-dev的工具,此搜索

的console.log

渲染项目列表, 您需要在地图中实际返回JSX

const renderList = () => {
  props.scores.map(item => <div key={item.id}>{item.name}</div>)
}

您应该阅读有关渲染react元素列表的最佳实践

编辑

由于scores是不确定的,因此您需要确保正确引用事物。

scorescombineReducers定义的关键吗? 亦称诸如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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM