setstate在react-native中无法正常工作
所以这里我有 3 个 TouchableOpacities ,每次按下 backgroundColor 都会改变它自己并且它工作正常,所以我尝试在我的 changeColor() 函数中添加一个 setState ,它返回这里按下的每个 TouchableOpacity 的大小(M、L 或 XL)是我的代码 :
constructor(props) {
super(props)
colorId: 0,
size:""
};
}
changeColor = (id) => {
this.setState({ colorId: id });
if (id == 1) {
this.setState({ size: 'M' })
}
else if (id == 2) {
this.setState({ size: 'XL' })
}
else {
this.setState({ size: 'L' })
}
console.log("Button id:", id ,"size :", this.state.size)
}
render() {
return (
<TouchableOpacity style={this.state.colorId === 2 ? styles.button_XL_Colored : styles.button_XL} onPress={() => this.changeColor(2)} ><Text style={{ color: '#000000', alignSelf: 'center', marginTop: normalize(12), fontSize: normalize(20) }}>XL</Text></TouchableOpacity>
<TouchableOpacity style={this.state.colorId === 3 ? styles.button_L_Colored : styles.button_L} onPress={() => this.changeColor(3)}><Text style={{ color: '#000000', alignSelf: 'center', marginTop: normalize(12), fontSize: normalize(20) }}>L</Text></TouchableOpacity>
<TouchableOpacity style={this.state.colorId === 1 ? styles.button_M_Colored : styles.button_M} onPress={() => this.changeColor(1)} ><Text style={{ color: '#000000', alignSelf: 'center', marginTop: normalize(12), fontSize: normalize(20) }}>M</Text></TouchableOpacity>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5F5F8',
},
button_M: {
backgroundColor: '#FFFDFD',
borderRadius: 10,
width: normalize(50),
height: normalize(50),
alignSelf: 'center',
marginLeft: 0,
marginTop: normalize(-10)
},
button_L: {
backgroundColor: '#FFFDFD',
borderRadius: 10,
width: normalize(50),
height: normalize(50),
alignSelf: 'center',
marginLeft: normalize(140),
},
button_XL: {
backgroundColor: '#FFFDFD',
borderRadius: 10,
width: normalize(50),
height: normalize(50),
alignSelf: 'center',
},
button_M_Colored: {
backgroundColor: '#D05A0B',
borderRadius: 10,
width: normalize(50),
height: normalize(50),
alignSelf: 'center',
marginLeft: 0,
marginTop: normalize(-10)
},
button_XL_Colored: {
backgroundColor: '#D05A0B',
borderRadius: 10,
width: normalize(50),
height: normalize(50),
alignSelf: 'center',
},
button_L_Colored: {
backgroundColor: '#D05A0B',
borderRadius: 10,
width: normalize(50),
height: normalize(50),
alignSelf: 'center',
marginLeft: normalize(140),
},
回答
您使用console.log之后setState,上述业绩预计,因为setState是异步的。Soconsole.log以旧状态而不是新状态执行(新状态尚未分配)。
您需要使用 的回调形式setState来获得正确的状态。
this.setState({ size: 'L' }, (state) => console.log("Button id:", id ,"size :",state.size))
您可以在此处阅读更多相关信息:https : //reactjs.org/docs/react-component.html#setstate
// 添加(我没有足够的代表来评论)
我看到 John Lim 的回答建议使用await,但setState没有返回 a Promise,所以await在这里不起作用。https://github.com/facebook/react/blob/0e100ed00fb52cfd107db1d1081ef18fe4b9167f/packages/react/src/ReactBaseClasses.js#L57-L66