使用map函数遍历数组时如何更新一个特定元素的状态。
<View style={{ marginBottom: 20 }}>
{
this.props.addresses.map(addr => {
return (
<View style={{ marginRight: 10 }} key={addr.label}>
<View>
<Text style={styles.labelTextStyle}>{addr.label}</Text>
</View>
</View>
);
})
}
</View>
触发事件时如何更新一个特定元素(addr.label)的状态?
您不能直接在循环中调用setState
来自react docs:
setState()不会立即使this.state突变,而是创建一个挂起的状态转换。调用此方法后访问this.state可能会返回现有值。无法保证对setState的调用的同步操作,并且可以为提高性能而对调用进行批处理。
你能做的是
eventHandler(idx, val) {
var newState = {}
newState[idx] = val;
this.setState(newState);
}
在视图中,假设您有一个需要触发处理程序的按钮
<View style={{ marginBottom: 20 }}>
{
this.props.addresses.map(addr, idx => {
return (
<View style={{ marginRight: 10 }} key={addr.label}>
<View>
<Text style={styles.labelTextStyle}>{addr.label}</Text>
<Button onPress={this.eventHandler.bind(this, idx, addr.label}><Button>
</View>
</View>
);
})
}
</View>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句