Fetch响应返回{artists: null}时如何移除已渲染的items
问题原因
你当前的代码存在两个核心问题:
- 渲染
artistDetailMusic模块的逻辑仅判断了用户登录状态,完全未关联接口返回的艺术家数据状态,不管接口有没有拿到有效数据,只要用户登录就会渲染这个模块 - 没有对
data.artists === null的场景做兼容处理,这种情况下直接访问data.artists[0]会抛出语法错误,直接中断后续逻辑执行
修复方案
你需要新增一个状态变量存储接口返回的艺术家数据,再把渲染逻辑和这个状态绑定即可,具体修改如下:
- 首先在对应作用域新增状态变量存储艺术家数据
// 新增:存储艺术家接口返回数据 let artistData = null; const isLoggedIn = app.session.user; const artistTitle = this.attrs.discussion.title().split(/\s+/).join('%20'); const languageCode = app.forum.attribute('justoverclock-theaudiodb-api.langCode') || 'EN'; // gestiamo gli errori nella risposta function handleErrors(response) { if (!response.ok) { throw Error(response.statusText); } return response; }
- 修改fetch回调逻辑,兼容无数据场景,同步更新状态变量
if (isLoggedIn) { const artistApi = fetch('https://theaudiodb.com/api/v1/json/1/search.php?s=' + artistTitle) .then(handleErrors) .then((response) => response.json()) .then((data) => { console.log(data) // 新增:判断artists是否为空 if (!data.artists || data.artists.length === 0) { artistData = null; m.redraw(); return; } artistData = data.artists[0]; const arrayElem = 'strBiography' + languageCode; if (artistData[arrayElem] === null) { artistData[arrayElem] = 'Oops! Description is not available in your language unfortunately...You can contribute to TheAudioDB.com by adding information about this artists in your language.'; } const descArt = (document.getElementById('descArtist').innerText = artistData[arrayElem].substring(0, 400) + '...'); const thumbArtists = (document.getElementById('imgArtists').src = artistData.strArtistThumb); const genreArtist = (document.getElementById('genreArtist').innerText = app.translator.trans('justoverclock-theaudiodb-api.forum.genres') + ': ' + artistData.strStyle); const yearBorn = (document.getElementById('yearBorn').innerText = app.translator.trans('justoverclock-theaudiodb-api.forum.intFormedYear') + ': ' + artistData.intFormedYear); const countryArtist = (document.getElementById('strcountry').innerText = app.translator.trans('justoverclock-theaudiodb-api.forum.countryart') + ': ' + artistData.strCountry); m.redraw(); }) .catch((error) => { console.log('This Artist does not exist ;) =>', artistTitle) // 新增:请求出错时清空状态 artistData = null; m.redraw(); }); }
- 修改extend渲染逻辑,新增对艺术家数据状态的判断
extend(DiscussionHero.prototype, 'items', function (items) { const isLoggedIn = app.session.user; // 新增:只有同时满足登录、有有效艺术家数据两个条件才渲染模块 if (isLoggedIn && artistData) { items.add( 'artistDetailMusic', <div class="artistWrapper"> <div id="containerArtist"> <div id="contentArtist"> <p class="artistDesc" id="descArtist"/> <div class="itemdescrip"> <div class="genreArtist" id="genreArtist"/> <div class="yearBorn" id="yearBorn"/> <div class="strcountry" id="strcountry"/> </div> </div> </div> <div id="sidebarImgArtist"> <img className="imgArtist" id="imgArtists" src=""/> </div> </div> ); } });
修改完成后,只要接口未返回有效艺术家数据,模块就不会渲染,符合你要的隐藏需求。
内容的提问来源于stack exchange,提问作者juniorDevFla
相关产品推荐
相关产品推荐

