Reputation: 21
I have a strange issue. I am working with a list of components in a parent component. Basically I want to change one of the props and to reset all of the child components.
Here is the code I'm using to do that.
for (let i = 0; i < this.numOfNodes; i ++){
let idNum = 'a' + i;
this.passNodes[i] = idNum;
let num = Math.floor(Math.random() * this.numOfMeetings);
this.nodeMeeting[idNum] = this.meetings[num];
let iid = this.passNodes[i];
this.nodes[i] = <Person infected = {false} reset = {true} id={iid} meeting={this.nodeMeeting[iid]} parentCallback = {this.callbackFunction} key={iid}/>
}
console.log(this.nodes[0])
console.log(this.nodes)
This issue I am having, is with the two log statements at the bottom. For the first log statement, it prints the index into the list and in the props, reset is true, as I want it.
However, in the second log statement, when I print out the entire this.nodes, it seems that each of them haven't been updated as reset is still false for all the nodes.
I was wondering if I could get some help.
Upvotes: 0
Views: 47
Reputation: 197
Your issue most likely is being caused by the page not re-rendering, because you're not using States
Use States instead of trying to update the components like that, since the page only re-renders when you update/change the State, assignthis.nodes under the State of that component as this.state.nodes, then update the nodes with setState
Example code
export default class Component extends React.Component{
constructor(props){
super(props);
this.state = {
nodes: []
}
}
componentDidMount = () => {
// You can use Axios or whatever you use for getting the data from the
// Back-End
getNodes(nodes => {
// If I'm not wrong you should
// Be able to modify directly this.state.nodes array
// Then update it with this.setState()
// If I'm wrong then just assign it to a variable
// Though the variable is a reference to it, so it should work without
// Using a variable
for(let i = 0; i < this.state.nodes.length; i++){
// Your code
let idNum = 'a' + i;
this.passNodes[i] = idNum;
let num = Math.floor(Math.random() * this.numOfMeetings);
this.nodeMeeting[idNum] = this.meetings[num];
let iid = this.passNodes[i];
// Modified part this.nodes -> this.state.nodes
this.state.nodes[i] = <Person infected = {false} reset = {true} id={iid} meeting={this.nodeMeeting[iid]} parentCallback = {this.callbackFunction} key={iid}/>
}
// If you're using a variable to make the modifications, use that instead
// of this.state.nodes, so it'll be like this.setState({nodes: yourVar})
this.setState({nodes: this.state.nodes});
});
}
}
So basically transform this.nodes to be a State property, then update it via updating the State with setState and it will re-render the page and most likely will fix your issue.
See State and Lifecycle Documentation for more info.
Upvotes: 1