React native - 为什么它循环到最后?

React native - Why is it looping till the end?

我刚开始学习 React Native,我遇到了这个问题,我不明白为什么会这样。有人可以帮助我吗?

const [data, setData] = useState([])
const [itemModal, setItemModal] = useState(false)

const fetchingData = async () =>{
    var lista = [];
    var currentItem;
    const res = await fetch('http://mockapi.ddns.net/APIHandler.php');
    const things = await res.json();
    for(let i = 1; i <= 20; i++) {
        currentItem = things[i];
        lista.push(currentItem)
    }
    setData(lista)
}
useEffect(() => { 
    fetchingData();
  },[]);
<ScrollView>{data.map((item)=>{

        const {id, cijenaUKN, naslov, dostupneVelicine} = item;

        var urlNaslov = naslov.replace(/\//g, "").replace(/\’/g, "")

        return (
            <View key={id} style={{backgroundColor:"grey", borderWidth:2, borderColor:"black"}}>
                <TouchableOpacity onPress={()=>setItemModal(true)}>
                    {itemModal ? <Modal><Text>{id}</Text></Modal> : null}
                <Image source={{uri: `http://mockapi.ddns.net/YEE/${urlNaslov}/1.png`}} style={{backgroundColor:"aliceblue", width:100, height:100}}/>
                <Text>{id}</Text>
                <Text>{naslov}</Text>
                <Text>{cijenaUKN}</Text>
                <Text>{dostupneVelicine}</Text>
                </TouchableOpacity>
            </View>
        )
    })}
    </ScrollView>

我正在遍历产品数组,当我点击想要的产品模式时,应该会弹出该项目。但是每次我尝试时,都会弹出 Modal 并显示数组中最后一个元素的 ID。我不知道为什么会这样。 我试着把它赋值给变量(没用);

根据您的代码,您打开了所有模态框,因此它显示最后一个模态框在顶部,

做这样的事情

const [data, setData] = useState([])
const [itemModal, setItemModal] = useState(null)

const fetchingData = async () =>{
    var lista = [];
    var currentItem;
    const res = await fetch('http://mockapi.ddns.net/APIHandler.php');
    const things = await res.json();
    for(let i = 1; i <= 20; i++) {
        currentItem = things[i];
        lista.push(currentItem)
    }
    setData(lista)
}
useEffect(() => { 
    fetchingData();
  },[]);
<ScrollView>{data.map((item)=>{

        const {id, cijenaUKN, naslov, dostupneVelicine} = item;

        var urlNaslov = naslov.replace(/\//g, "").replace(/\’/g, "")

        return (
            <View key={id} style={{backgroundColor:"grey", borderWidth:2, borderColor:"black"}}>
                <TouchableOpacity onPress={()=>setItemModal(id)}>
                    {itemModal === id ? <Modal><Text>{id}</Text></Modal> : null}
                <Image source={{uri: `http://mockapi.ddns.net/YEE/${urlNaslov}/1.png`}} style={{backgroundColor:"aliceblue", width:100, height:100}}/>
                <Text>{id}</Text>
                <Text>{naslov}</Text>
                <Text>{cijenaUKN}</Text>
                <Text>{dostupneVelicine}</Text>
                </TouchableOpacity>
            </View>
        )
    })}
    </ScrollView>