简体   繁体   English

如何使用 react-select 5.3.2 在 React17 中设置 select 选项值并挂钩来自 API 的数据

[英]How to set select option value in React17 using react-select 5.3.2 and hooks with data from API

I am trying to set the selected value of my react-select from useState().我正在尝试从 useState() 设置我的反应选择的选定值。 I get my data from a API that I call in useEffect().我从在 useEffect() 中调用的 API 获取数据。 I have the data to populate the select options which is 'brandOptions ' below but after hit my API I am trying ty set my to what comes back from API = > setSelectedBrandOption({ label: data[0].brandPreference, value: data[0].brandPreference})... what I am I dong wrong?我有数据来填充 select 选项,这是下面的“brandOptions”,但在点击我的 API 之后,我正在尝试将我设置为从 API 返回的内容 => setSelectedBrandOption({ label: data[0].brandPreference, value: data[ 0].brandPreference})...我错了什么? Right now the dropdown doesn't change.现在下拉列表没有改变。

My data from API comes back like this:我从 API 返回的数据是这样的:

data: [
0: { brandPreference: "Huggies", currentSize: 2, firstName: "Roman" }
]

Here is my code:这是我的代码:

import React, { useState, useContext, useEffect } from 'react';
import Select from 'react-select';
import { UserContext } from '../context/UserContext';
import './Settings.css';

const brandOptions = [
  { value: 'Huggies', label: 'Huggies' },
  { value: 'Kirkland', label: 'Kirkland' },
  { value: 'Pampers', label: 'Pampers' },
  { value: 'Parents', label: "Parent's Choice" },
  { value: 'Up', label: 'Up & Up' },
];

const Settings = () => {
  const [kidsData, setKidsData] = useState([]);
  const { user, setUser } = useContext(UserContext);
  const [selectedBrandOption, setSelectedBrandOption] = useState({}); 

    useEffect(() => {
      const user_ID = user.user._id;
      const url = `/api/kids/${user_ID}`;
      const getKids = async () => {
        try {
          const headers = {
            'Content-Type': 'application/json',
            'x-auth-token': user.jwt,
          };
          const res = await fetch(url, {
            method: 'GET',
            headers: headers,
          });
          const data = await res.json();    
          setKidsData(data)   
          setSelectedBrandOption({
            label: data[0].brandPreference,
            value: data[0].brandPreference,
          });  
        } catch (error) {
          console.log(error)
        }
      }
      getKids(); 
    }, [])
    

  return (      
      <section>                      
            <Select
              onChange={setSelectedBrandOption}
              options={brandOptions}
              placeholder={'Select Brand Preference'}
            />               
       
      </section>     
  );
};

export default Settings;

I would try two things:我会尝试两件事:

1- Try setting the defaultValue prop in the Select component after the API request is made 1- 发出 API 请求后,尝试在 Select 组件中设置 defaultValue 属性

2- Switch to an async approach using AsyncSelect as it is exposed in the following issue: https://github.com/JedWatson/react-select/issues/2877 2- 切换到使用 AsyncSelect 的异步方法,因为它在以下问题中公开: https://github.com/JedWatson/react-select/issues/2877

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM