[英]Select value doesnt change the first time I trigger onChange event when using setSate React
[英]Select value doesn't change the first time I trigger onChange event
我有選擇菜單,當我使用optionSelect方法選擇一個選項時,我試圖更改一個值。 當我第一次選擇一個選項時,console.log 中的值沒有更新。 它只從第二次開始改變。 不知道我做錯了什么。 我是否需要在componentDidMount中添加一些東西!
constructor(props) {
super(props);
this.state = {
value : '',
};
}
optionSelect(option){
this.setState({value : option.target.value});
console.log(this.state.value)
}
render() {
return (
<React.Fragment>
<Select name="item"
required={this.props.required ? 'required' : ''}
defaultValue={this.state.value}
onChange={e => this.optionSelect(e)}
>
<option disabled value="">{this.props.placeholder}</option>
{
this.props.optionData && this.props.optionData.length ?
this.props.optionData.map(option => (
<option key={option.id} value={option.id}>
{option.name}
</option>
)) : null
}
</Select>
</React.Fragment>
);
}
React 中的 setState() 不是同步的。 當您嘗試 console.log 值時。 該值尚未更新。 如果要在值更改后立即對其進行控制台記錄,請添加
componentDidUpdate(){
console.log('Value', this.state.value)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.