Basically, I want to make my page reactive and give results based on user's input/choices.
I pass user's choices from parent to child component via props (dictionary is an object with user's choices and amount of choices per key (ex: dictionary = {Gallileo: 2, Juno: 1, Mars: 1}
):
<Childcomp aggregate={this.props.dictionary}/>
On the child component, I do a simple loop and the choice and number of votes into a state variable via componentWillMount()
method:
componentWillMount(){
let obj = this.props.aggregate // {Gallileo: 2, Juno: 1, Mars: 1}
let choice;
for(let key in obj){
if(key === this.props.option){
choice = obj[key];
break;
}
};
let total = 0;
for(let key in obj){
total += obj[key];
}
this.setState({choice: choice, total: total});
};
The problem I have with this is that the state variable does not change the value when input is received. this.props.aggregate
does change reactively, but everything after that doesn't respond.
I tried using Session variables to make it reactive, I tried to place the code in Tracker.autorun()
, but I have no luck.
The for loop on the object doesn't trigger at all, it seems, which explains why the state variable is never updated even though the this.props.aggregate prop updates seamlessly.
If props are changing, use the componentWillReceiveProps method.
componentWillReceiveProps(nextProps){
let obj = nextProps.aggregate // {Gallileo: 2, Juno: 1, Mars: 1}
let choice;
for(let key in obj){
if(key === nextProps.option){
choice = obj[key];
break;
}
};
let total = 0;
for(let key in obj){
total += obj[key];
}
this.setState({choice: choice, total: total});
};
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments