基本上,我想让我的页面反应并根据用户的输入/选择给出结果。
我通过道具将用户的选择从父组件传递到子组件(字典是一个具有用户选择的对象和每个键的选择数量(例如:dictionary = {Gallileo: 2, Juno: 1, Mars: 1}
):
<Childcomp aggregate={this.props.dictionary}/>
在子组件上,我通过componentWillMount()
方法做一个简单的循环以及对状态变量的选择和投票数:
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});
};
我遇到的问题是状态变量在收到输入时不会改变值。 this.props.aggregate
确实会被动地改变,但之后的所有内容都没有响应。
我尝试使用Session变量使其变为反应性,我尝试将代码放在Tracker.autorun()
中,但我没有运气。
对象上的for循环根本没有触发,这似乎解释了为什么状态变量永远不会更新,即使this.props.aggregate prop无缝更新。
答案 0 :(得分:1)
如果道具正在变化,请使用componentWillReceiveProps方法。
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});
};