React Native中Axios请求后如何在Map函数中初始隐藏指定索引数据
解决React Native中初始隐藏指定索引数据的问题
问题根源
你当前用单个布尔值show控制所有列表项的显示,在showItem函数里循环调用setShow时,状态会被最后一次循环的赋值覆盖(比如数据长度大于3的话,最后一个索引的show=true会覆盖之前的false),导致所有条目都跟着这个最终状态走,自然没法单独隐藏索引1和2的内容。
解决方案1:渲染时直接判断索引(最简方案)
如果只是初始隐藏指定索引,不需要后续动态切换显示状态,完全不用额外的show状态,直接在渲染map的时候判断索引即可:
修改后代码
首先删掉原来的const [show, setShow] = useState(true);和showItem()函数,然后修改UI部分:
<View style={styles.leftSideView}> {data && data.map((item, index) => ( <TouchableOpacity key={item.id} style={styles.leftViewStyle}> {/* 只显示索引不是1和2的条目 */} {index !== 1 && index !== 2 && ( <Text style={styles.leftView}>{item.name.en}</Text> )} </TouchableOpacity> ))} </View>
解决方案2:用状态数组控制(支持动态切换)
如果后续需要动态切换这些条目的显示/隐藏,就需要给每个条目单独维护显示状态,用数组来存储:
修改后代码
// 初始化状态数组,默认所有条目都显示 const [itemVisible, setItemVisible] = useState([]); axios .get('url', { headers: { 'Content-Type': 'application/json', Authorization: `Bearer token-key`, }, }) .then(response => { const data = response.data; setData(data); // 初始化显示状态:索引1和2设为false,其余为true const initialVisible = data.map((_, index) => index !== 1 && index !== 2); setItemVisible(initialVisible); }) .catch(error => { console.log('error', error.response); });
UI部分修改为:
<View style={styles.leftSideView}> {data && data.map((item, index) => ( <TouchableOpacity key={item.id} style={styles.leftViewStyle}> {itemVisible[index] && ( <Text style={styles.leftView}>{item.name.en}</Text> )} </TouchableOpacity> ))} </View>
后续如果需要切换某个索引的显示状态,只需要修改itemVisible数组对应位置的值即可。
内容的提问来源于stack exchange,提问作者Garima Garg
相关产品推荐
相关产品推荐

