在我的代码中,我试图使用REACT JS中的事件方法为特定的状态变量设置一个值。并以折扣价进行一些计算。 计算后,将更新后的值设置为状态。但是,只要下一个事件发生,它就应该最近更新。
this.state = {
isAddVariant: false,
vendors: [],
variant_price: '',
variant_priceDiscount: '',
variant_priceDiscounted: '',
variant_unit: '',
variants: [],
}
onVariantType = (e) => {
this.setState({
[e.target.name]: e.target.value,
})
if (e.target.name === 'variant_price' || e.target.name === 'variant_priceDiscount') {
let variant_priceDiscounted = this.state.variant_priceDiscount !== '' ? (this.state.variant_price - (this.state.variant_price * (this.state.variant_priceDiscount / 100))).toFixed(2) : this.state.variant_price
this.setState({ variant_priceDiscounted })
}
}
//渲染功能
<Typography variant="h7" color="inherit" style={{ marginTop: 20 }}>
Add Product Variants
</Typography>
<Grid container spacing={24}>
{/* Input - Price */}
<Grid item xs={2}>
<TextField
type={'number'}
name={'variant_price'}
value={nullToEmptyString(variant_price)}
onChange={this.onVariantType}
label={'Price'}
placeholder={'Enter price in ₹'}
required={true}
margin={'dense'}
autoComplete={'off'}
fullWidth
/>
</Grid>
{/* Input - Unit */}
<Grid item xs={2}>
<TextField
name={'variant_unit'}
value={nullToEmptyString(variant_unit)}
onChange={this.onVariantType}
label={'Unit'}
placeholder={'Enter unit (eg: kg)'}
required={true}
margin={'dense'}
autoComplete={'off'}
fullWidth
/>
</Grid>
{/* Input - Discount */}
<Grid item xs={2}>
<TextField
type={'number'}
name={'variant_priceDiscount'}
value={nullToEmptyString(variant_priceDiscount)}
onChange={this.onVariantType}
label={'Discount'}
placeholder={'Enter discount in %'}
margin={'dense'}
autoComplete={'off'}
fullWidth
/>
</Grid>
<Grid item xs={4}>
<TextField
type={'number'}
name={'variant_priceDiscounted'}
value={nullToEmptyString(variant_priceDiscounted)}
label={'Discounted Price'}
margin={'dense'}
autoComplete={'off'}
disabled
fullWidth
/>
</Grid>
<Grid item xs={2}>
{/* Button - Add */}
<IconButton
type={'add'}
aria-label={'Add'}
color={'primary'}
onClick={this.onAddVariant}
>
<IconCheck />
</IconButton>
</Grid>
</Grid>
预期行为已更新。折现值已计算并立即显示。
实际行为是最近更新的值实际行为图片:
答案 0 :(得分:1)
setState
是async
,需要一些时间来更新状态。 setState
需要一个callback,您可以使用它,
onVariantType = (e) => {
let name = e.target.name; //store the name in a variable to use in callback
this.setState({
[e.target.name]: e.target.value,
}, () => {
if (name === 'variant_price' || name === 'variant_priceDiscount') {
let variant_priceDiscounted = this.state.variant_priceDiscount !== '' ? (this.state.variant_price - (this.state.variant_price * (this.state.variant_priceDiscount / 100))).toFixed(2) : this.state.variant_price
this.setState({ variant_priceDiscounted })
}
})
}
注意:我们将e.target.name
存储在name
变量中,因为在seState
之后,execute的e
无效。进一步了解Synthetic events
。