ESLint报map回调需返回值错误导致Netlify部署失败如何解决
问题原因
ESLint抛出array-callback-return错误,是因为你在Array.prototype.map()的回调函数中,仅在条件匹配时返回了React节点,条件不匹配的分支执行return;隐式返回了undefined,违反了该规则要求的所有分支都必须有明确返回值的规定。
修复方案
方案1:先过滤后遍历(最优)
先把不符合条件的项用filter过滤掉,再执行map渲染,这样所有map的回调都有明确的返回值,同时还能减少不必要的遍历,性能更好。
修改后的Content组件代码如下:
const Content = () => countries?.length && countries.map((country) => { // 先过滤出当前国家对应的联赛 return allLeagues .filter(league => league.leagueCountry === country) .map((league, index) => { // 再过滤出当前联赛+国家对应的赛事 return matches .filter(match => match.leagueName === league.leagueName && match.leagueCountry === country) .map((match) => { return ( <div> <div key={index} className='fixtures_container'> <div className='comp_header'> <div className='img_container'> <img className='competition_logo' src={match.leagueFlag} alt={`flag of ${match.leagueCountry}`} width='20' height='15' /> </div> <Link className='competition_name'>{match.leagueCountry}</Link> <Link className='league_group'>{match.leagueName} - {match.leagueRound}</Link> <span className='date'>{AppendToday()}</span> </div> {match.matches.map((fixture, subIndex) => { return ( <div key={subIndex} className='fixtures'> <div className='live_match' style={{backgroundColor: fixture.fixture.status.elapsed && fixture.fixture.status.long !== 'Match Finished' ? 'orange' : 'black'}}></div> <div className='timestamp'>{fixture.fixture.status.long === 'Not Started' ? '' :fixture.fixture.status.long === 'Time to be defined' ? '' :fixture.fixture.status.long === 'Match Postponed' ? 'postp' :fixture.fixture.status.long === 'Match Finished' ? 'FT' : `${fixture.fixture.status.elapsed}'`} </div> <div className='teamOne_teamTwo_scoreSheet'> <div className='teams'> <div className='team'>{fixture.teams.home.name}</div> <div className='score'>{fixture.fixture.status.long === 'Not Started' ? '?' : fixture.fixture.status.long === 'Match Finished' ? fixture.goals.home : fixture.fixture.status.elapsed ? fixture.goals.home : '?'} </div> </div> <div className='teams'> <div className='team'>{fixture.teams.away.name}</div> <div className='score'>{fixture.fixture.status.long === 'Not Started' ? '?' : fixture.fixture.status.long === 'Match Finished' ? fixture.goals.away : fixture.fixture.status.elapsed ? fixture.goals.away : '?'} </div> </div> </div> <div className='star'> <FontAwesomeIcon icon = {faStar} /> </div> </div> ) })} </div> </div> ) }) }) })
方案2:不符合条件的分支返回null(快速修复)
如果不想改动现有逻辑结构,只需要把原有条件判断后的return;改成return null;即可,明确返回空节点,符合ESLint规则要求,示例如下:
// 原有两处条件判断都按这个格式修改即可 if (league.leagueCountry !== country) return null;
额外优化建议
你当前useDeepCompareEffect的依赖数组包含了allLeagues、setIdResponse、countries、matches这几个内部变量/state,会触发无限重渲染:effect执行时会修改这些state,state变化又会触发effect重新执行,形成死循环。建议把依赖数组简化为仅保留fixtures即可,其余变量都是基于fixtures计算得到,不需要加入依赖:
useDeepCompareEffect(() => { // 原有逻辑保持不变 }, [fixtures])
内容的提问来源于stack exchange,提问作者therepositor
相关产品推荐
相关产品推荐

