I have a series of data that contains some objects in one array(json file) and it will be shown in React. The main problem is that the value of index_ in onClick={e => this.handelruleRoom(e, element.families[j], index)} function in for loop always shows the last one. For example lenfamilies is 3 , when ever I click <span key={index} onClick={e => this.handelruleRoom(e, element.families[j], index)}>Click</span> with key=1in console the value of index_ is 3.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
DetailsInfo: {},
text:{}
}
}
render() {
const { data } = this.state;
const renderInfo = data.map((item, i) => {
return (
<div class="item">
<div class="moreInfo" onClick={e => this.showDiv(e, item, i)}>
<span>show more data</span>
</div>
<div class="table">{this.state.DetailsInfo[i]}</div>
</div>
)
})
return <div>{renderInfo}</div>;
}
showDiv = (e, element, i) => {
this.setState(prevState => ({
DetailsInfo: { ...prevState.DetailsInfo, [i]: this.renderDetails(element, i) },
}))
}
renderDetails(element,i){
let lenfamilies = element.families.length
var indents =[];
var index=0;
for(var j = 0 ;j <lenfamilies;j++){
var numF = i;
var numS = j;
var stingF = numF.toString();
var stingS = numS.toString();
index= stingF+stingS
indents.push(<div>
<span key={index} onClick={e => this.handelrule(e, element.families[j], index)}>Click</span>
<span class="text" key={index}>{this.state.text[index]}</span></div>
)
}
return(
indents
)
}
handelrule = (e, element, index) => {
console.log(index)
this.setState( prevState => ({
text: { ...prevState.text, [index]: 'test'},
}))
}
}
ReactDOM.render(<App />, document.getElementById("Result"));
letinstead ofvarforjvariable. but there is no different;|