我有一组4人
的TextInput
前三个设置'onChange'方法的值ok,但最后一个没有设置?
onChange(index : number, value : string) {
console.log(`onChange with index ${index} and val ${value}`);
switch (index) {
case 0:
console.log('capador 1');
this.setState({firstVal : value});
break;
case 1:
console.log('capador 2');
this.setState({secondVal : value});
break;
case 2:
console.log('capador 3');
this.setState({thirdVal : value});
break;
case 3:
console.log('capador 4');
this.setState({fourthVal : value});
break;
}
if (index === 3) {
console.log(`ya aya con input : ${this.state.firstVal}`);
console.log(`ya aya con input : ${this.state.secondVal}`);
console.log(`ya aya con input : ${this.state.thirdVal}`);
console.log(`ya aya con input : ${this.state.fourthVal}`); // why not setting?
}
}
所以我可以在控制台日志中看到值是正确的,但是在索引=== 3上,没有返回值。
这是日志:
onChange with index 0 and val 1
capador 1
onChange with index 1 and val 2
capador 2
onChange with index 2 and val 3
capador 3
onChange with index 3 and val 4
capador 4
ya aya con input : 1
ya aya con input : 2
ya aya con input : 3
ya aya con input :
这就是TextInputs的样子:
<TextInput
ref="third"
style={this.state.pos > 1 ? styles.textInputStyle : styles.textInputNormalStyle}
keyboardType = "number-pad"
maxLength={1}
onKeyPress={(event) => {this.onChange(2, event.nativeEvent.key); }}
/>
答案 0 :(得分:1)
setState
没有立即设置值,您必须等待状态更新。您可以检查状态更新时调用的setState
回调中的值。请考虑以下代码段
this.setState({fourthVal : value}, () => {
console.log(`ya aya con input : ${this.state.firstVal}`);
console.log(`ya aya con input : ${this.state.secondVal}`);
console.log(`ya aya con input : ${this.state.thirdVal}`);
console.log(`ya aya con input : ${this.state.fourthVal}`);
});
希望这会有所帮助!