[英]Resetting state of react-select component not working
我的 react-select 組件有兩個問題:
第一個:當我設置 select 和選項時,我無法在設置 select 組件后更改選項第二個:當我的表單重置時,它不會重置 react-select 組件。
出於實際原因,這只是與問題本身有關,所以我故意留下其他輸入字段並盡可能保持簡短
以下是我正在使用的示例。 我使用異步請求從 api 獲取我的選項,好消息是選項填充。 我遇到的問題是,一旦我選擇了一個選項,我就無法更改它,並且當我提交表單時,所有其他字段而不是 select 組件都會重置。 我必須重新加載頁面才能重置組件。 我能做些什么來糾正這個問題?
import React, { Component } from 'react'
import Select from 'react-select'
import axios from 'axios'
import '../index.css'
class RecipeInput extends Component{
constructor(props){
super(props)
this.state = {
category_id:'',
name:'',
ingredients:'',
chef_name:'',
origin:'',
instructions:'',
}
}
async options(){
const BASE_URL = `http://localhost:3002`
const CATEGORIES_URL =`${BASE_URL}/categories`
const res = await axios.get(CATEGORIES_URL)
const data = res.data
const options = data.map(options => ({
'label' : options.category,
'id' : options.id
}))
this.setState({category_id: options})
}
handleSelect = (event) =>{
this.setState({category_id:event.id})
}
componentDidMount(){
this.options()
}
handleReset = () =>{
this.setState({ name:'', ingredients: '', chef_name: '', origin: '',instructions: '', category_id:''})
}
handleSubmit = (event) =>{
event.preventDefault();
this.props.postRecipes(this.state)
this.handleReset()
}
render(){
let dropdown = 'form-select form-select-sm'
return(
<div>
<form onSubmit={(event)=>this.handleSubmit(event)} noValidate>
<Select options={this.state.category_id} value={this.state.category_id} onChange={(event)=>this.handleSelect(event)} className={dropdown}/>
<input value='submit' type='submit' />
</form>
</div>
)
}
}
export default RecipeInput
我認為您對 select 元素上的選項數組和 value 屬性使用相同的 category_id state 變量。 您需要為選項屬性提供選項數組和將更改為值屬性的 category_id state 變量。
所以有一個小細節我沒有人發現。 我記得的一個問題是,當您提交一個表單,其中一部分在其中發出異步請求時,組件會卸載,並且您必須在重置表單時再次安裝它。
這是我對 api 的異步調用
async options(){
const BASE_URL = `http://localhost:3002`
const CATEGORIES_URL =`${BASE_URL}/categories`
const res = await axios.get(CATEGORIES_URL)
const data = res.data
const options = data.map(options => ({
'label' : options.category,
'id' : options.id
}))
this.setState({category_id: options})
}
這是加載頁面時組件安裝的位置。
componentDidMount(){
this.options()
}
好吧,當您提交表單時,上面的行基本上會卸載,而我沒有在表單重置時重新安裝它。
這是解決它的解決方案。
handleReset = () =>{
this.setState({ name:'', ingredients: '', chef_name: '', origin: '',instructions: '',category_id:''})
}
handleSubmit = (event) =>{
event.preventDefault();
this.props.postRecipes(this.state)
this.handleReset()
this.getOptions()
}
您會在上面注意到,當我與提交按鈕交互時,我只是重新安裝了this.getOptions() 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.