gpt4 book ai didi

javascript - 如何在 react-bootstrap select FromControl 中获取所选选项的值

转载 作者:行者123 更新时间:2023-11-30 11:32:56 25 4
gpt4 key购买 nike

我正在尝试根据存储在组件状态中的值将用户从下拉列表中选择的内容写入 firebase 数据库,但我不知道如何获取所选选项的值并将其更新为storeType 状态

这是我的下拉菜单:

<FormGroup>
<FormControl
componentClass="select"
placeholder="Store type"
onChange={this.handleCatChange}
>
<option value="placeholder">Choose eatery type...</option>
<option value="cafe">Cafe</option>
<option value="bakery">Bakery</option>
<option value="pizza">Pizza store</option>
<option value="sushi">Sushi store</option>
<option value="buffet">Buffet</option>
<option value="donut">Donut store</option>
<option value="other">Other</option>
</FormControl>
</FormGroup>

this.handleCatChange:

handleCatChange(e) {
this.setState({
storeType: e.target.value
})
console.log(this.state.storeType)
}

最佳答案

您的状态有效,但在您执行 console.log 时无效。这是因为 setState 是异步的,不会立即改变您的状态值。

根据 the docs ,

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

如果您需要在调用 setState 后确保事件的顺序,您可以传递一个回调函数。

this.handleCatChange

handleCatChange(e) {
this.setState({
storeType: e.target.value
}, () => console.log(this.state.storeType))
}

关于javascript - 如何在 react-bootstrap select FromControl 中获取所选选项的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45612278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com