My goal of this code:
- Render some view elements with a loop
- Inside the loop, set the state
- On clicking the elements, update that value
Here is my code:
import React, {Component} from 'react';
import {View, Text, TouchableOpacity} from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
maths: {},
};
}
prepareMaths = function() {
var count = 5;
var updateMath = key => {
var stateMaths = this.state.maths;
stateMaths['position_' + key] = Math.random();
this.setState({maths: stateMaths}, () => {
console.log(this.state.maths);
});
};
var stateMaths = this.state.maths;
return [...Array(count)].map((options, key) => {
stateMaths['position_' + key] = Math.random();
this.setState({maths: stateMaths});
return (
<TouchableOpacity
key={key}
onPress={() => updateMath(key)}
style={{
height: 100,
width: 200,
marginRight: 20,
marginBottom: 10,
backgroundColor: 'green',
}}>
<Text>{this.state.maths['position_' + key]}</Text>
</TouchableOpacity>
);
});
};
render() {
return (
<View>
<View>{this.prepareMaths()}</View>
</View>
);
}
}
I'm getting this error with this code:
I'm very confused. Because if I remove setState... code inside the loop, it's showing random maths naturally. But how? Since I'm using this.state.maths['position_' + key] on render. I really don't know how that data is generating.
Please help. Thanks in advance.

this.setState({maths: stateMaths});in the mapping loop?