循环遍历对象数组时出现空值错误
2019-10-28
191
我正在从 NHL API(使用 react、redux 和 fetch api)获取数据,并尝试显示球队名单信息。当我在控制台中记录组件中的名册 api 响应时,它可以正常工作并显示对象数组,但是当我尝试循环遍历它时,我收到一个错误,提示响应为 null。
这是保存响应的 rosterList 的样子: https://gyazo.com/3f14d24b3a5bfb3610b470abedb6fcca
这是 redux 操作:
// Redux action
export const getRoster = id => async dispatch => {
try {
setLoading();
const res = await fetch(
`https://statsapi.web.nhl.com/api/v1/teams/${id}?expand=team.roster`
);
const data = await res.json();
dispatch({
type: GET_TEAM_ROSTER,
payload: data['teams'][0].roster.roster
});
} catch (err) {
dispatch({
type: TEAM_ERROR,
payload: err.response
});
}
};
以及 redux 状态:
case GET_TEAM_ROSTER:
return {
...state,
currentRoster: action.payload,
loading: false
};
最后是我尝试渲染的组件列表:
import React, { useEffect, useState } from 'react';
import styles from './teamroster.module.css';
import { getRoster } from '../../actions/teamActions';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
const TeamRoster = props => {
const id = props.teamId;
let rosterList = props.team.currentRoster;
console.log(rosterList);
useEffect(() => {
props.getRoster(id);
// eslint-disable-next-line
}, []);
return (
<div className={styles.rosterContainer}>
<p>This is the team roster</p>
<ul>
/*********** Error here, cannot read length of null ********/
{!props.loading && rosterList.length === 0 ? (
<p>No players available</p>
) : (
rosterList.map((player, index) => (
<li key={index}>{player.jerseyNumber}</li>
))
)}
</ul>
</div>
);
};
TeamRoster.propTypes = {
getRoster: PropTypes.func.isRequired
};
const mapStateToProps = state => ({
team: state.team
});
export default connect(
mapStateToProps,
{ getRoster }
)(TeamRoster);
我不知道问题出在哪里,希望得到任何指导。谢谢。
1个回答
rosterList.length 返回未定义,因为组件是在 rosterList 从 API 返回之前首次呈现的。添加检查以确保在尝试调用 '.length' 之前 rosterList 存在。
代码如下所示:
<ul>
{props.loading || !rosterList ? (
<p>No players available</p>
) : (
rosterList && rosterList.map((player, index) => (
<li key={index}>{player.jerseyNumber}</li>
))
)}
</ul>
JakeD
2019-10-28