Issue
I have a problem, I consume a service that brings me a button array for a dynamic menu. This array I want to put in the screen, like button has an id for an action in specific.
Code
var sizes = []
for (var i = 0; i < this.state.tallas.length; i++) {
sizes.push(
<TouchableOpacity style={[styles.clothingSizeItem, this.state.idSize === this.state.tallas[i].id ? styles.activeClothingSizeItem:null]}
onPress={() => this.fetchSizeData(this.state.tallas[i].id)}>
<Text style={this.state.idSize === this.state.tallas[i].id ? styles.activeSizeText:null}>
{this.state.tallas[i].name}
</Text>
</TouchableOpacity>
);
}
render() {
return(
<View>
{sizes}
</View>
)
}
The problem is when I press a button from my dynamic menu, the button calls a function that receives a parameter, but this parameter comes from the service array. So I used the "i" param from for, but this variable ("i") can't be found after the screen was rendered.
Screen Shot error screen
Gracias!
Solution
You can use Array#map instead of a for loop:
const sizes = this.state.tallas.map(item => (
<TouchableOpacity style={[styles.clothingSizeItem, this.state.idSize === item.id ? styles.activeClothingSizeItem:null]}
onPress={() => this.fetchSizeData(item.id)}>
<Text style={this.state.idSize === item.id ? styles.activeSizeText:null}>
{item.name}
</Text>
</TouchableOpacity>
);
The reason the for
loop doesn't work here is that the index variable i
is incremented on every iteration of the loop, so by the time the callback ends up being called (long after the loop has completed), the value i
is always it's final value (same as tallas.length
).
Answered By - jevakallio
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.