reactjs 如何将Select标记的值从react-select设置为状态

wgxvkvu9  于 2022-12-29  发布在  React
关注(0)|答案(1)|浏览(155)

我正在尝试设置当我从“react-select”的标签中选择多个值时收到的值。
目前它抛出未定义,当我从标签中选择值时,我需要的状态的结果是:

['user._id','user._id','user._id'.....] so on depends on how many user i select

以下是我到目前为止所做的,但对我来说并不成功。

const [ selectedMembers , setSelectedMembers ] = useState<any>([]);
  const [options, setOptions] = useState([{value: "", label: ""}]);

//In useEffect i am making API Call and received the values in **res.data.data**
//the options will be displayed in select tag , 
  if(res.data.data){
      let option: any = [];
      res.data.data.map((admin, index) => {
      option.push({value: admin._id, label: admin.displayName})       
      })
      setOptions(option);
      }

  async function onChangeSelectedMembers(e){
    console.log(e)
    setSelectedMembers([...selectedMembers , e.value])
  }
//outcome of console.log(e) when i select values from Select tag is [Note : its dynamic //if i remove any user or add more user it changes accordinly :
// 0: {value: '61dfcfb71f492f4f4f589e93', label: 'hello_1'}
// 1: {value: '61dedd23bd15322626dd7539', label: 'hello_2'}

//DISPLAY SELECT TAG WITH VALUES 
return(
   <label className="form-label">{intl.formatMessage({ id: 'SELECT.MEMBERS' })}</label>
      <Select
         className="form-select, form-select-solid, basic-multi-select"
         isMulti
         onChange={(e)=>onChangeSelectedMembers(e)}
         options={options}
       >
 )

这是到目前为止我的试用版,但我收到了“未定义”的值在selectedMembers。任何人可以帮助我吗?将不胜感激!谢谢!

2lpgd968

2lpgd9681#

您需要修复onChangeSelectedMembers函数。请尝试按以下方式使用:

const [ selectedMembers , setSelectedMembers ] = useState<any[]>([]);
const [options, setOptions] = useState([{value: "", label: ""}]);

//In useEffect i am making API Call and received the values in **res.data.data**
//the options will be displayed in select tag , 
if(res.data.data){
    let option: any[] = [];
    res.data.data.map((admin, index) => {
      option.push({value: admin._id, label: admin.displayName})       
    })
    setOptions(option);
}

function onChangeSelectedMembers(opts){
    console.log(opts)
    setSelectedMembers(opts.map(opt => opt));
}
//outcome of console.log(e) when i select values from Select tag is [Note : its dynamic //if i remove any user or add more user it changes accordinly :
// 0: {value: '61dfcfb71f492f4f4f589e93', label: 'hello_1'}
// 1: {value: '61dedd23bd15322626dd7539', label: 'hello_2'}

//DISPLAY SELECT TAG WITH VALUES 
return(
   <label className="form-label">{intl.formatMessage({ id: 'SELECT.MEMBERS' })}</label>
   <Select
      className="form-select, form-select-solid, basic-multi-select"
      isMulti
      value={selectedMembers}
      onChange={onChangeSelectedMembers}
      options={options}
   >
 )

相关问题