获取数据后所选选项未显示在下拉占位符中

问题描述 投票:0回答:1

我正在开发一个项目,使用 Laravel API 从数据库中获取数据。该数据用于填充动态下拉列表。当我从下拉列表中选择一个选项时,会根据所选选项返回正确的数据,但选择后所选选项不会显示在下拉列表的占位符栏中。 这是我的代码的相关部分:

import { useState, useEffect } from "react";
import axios from "axios";
import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from "@headlessui/react";
import { CheckIcon, ChevronDownIcon } from "@heroicons/react/20/solid";
import { HiOutlineUserGroup } from "react-icons/hi2";

export default function SelectCategory({ onChange ,value}) {
  const [categoryData, setCategoryData] = useState([]);
  const [selectedCategory, setSelectedCategory] = useState(null); // Initially no category selected

  useEffect(() => {
    axios
      .get("http://127.0.0.1:8000/api/tourCategory")
      .then((response) => {
        const data = response.data || [];
        setCategoryData(data);
      })
      .catch((error) => {
        console.error("Error fetching category:", error);
      });
  }, []);

  const handleCategoryChange = (category) => {
    console.log("Selected Category:", category); // Debugging line
    setSelectedCategory(category.category);
    if (onChange) {
      onChange(category.category); // Pass the entire category object or adjust as needed
    } else {
      console.error("onChange function is not defined");
    }
  };
  
  return (
    <Listbox value={selectedCategory} onChange={handleCategoryChange}>
      <div className="relative">
        <ListboxButton className="relative w-full h-[5vw] border-x-[0.1vw] cursor-default text-center text-gray-900 hover:ring-1 hover:ring-inset hover:ring-gray-300 focus:outline-none ">
          <span className="mx-[0.5vw] border-b-[0.1vw] flex justify-between">
            <div className="mr-[0.7vw]">
              <HiOutlineUserGroup className="text-black h-[1.7vw] w-[1.7vw]" />
            </div>
            <label className="font-semibold mr-[0.7vw] text-[1.5vw]">Category</label>
            <div>
              <ChevronDownIcon
                aria-hidden="true"
                className="h-[2vw] w-[2vw] text-gray-800"
              />
            </div>
          </span>
          <span>
            <span className="ml-[1vw] text-sm text-gray-500 block truncate">
              {selectedCategory ? selectedCategory.category : "Select a category"}
            </span>
          </span>
        </ListboxButton>

        <ListboxOptions className="absolute z-10 mt-1 max-h-[20vw] w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
          {categoryData.length > 0 ? (
            categoryData.map((category, index) => (
              <ListboxOption
                key={index}
                value={category}
                className="group relative cursor-default select-none py-2 pl-3 pr-9 text-gray-900 hover:bg-[#247D7E] hover:text-white"
              >
                <div className="flex items-center">
                  <span className="block truncate font-normal group-data-[selected]:font-semibold">
                    {category.category}
                  </span>
                </div>
                <span className="absolute inset-y-0 right-0 flex items-center pr-4 text-[#247D7E] group-data-[focus]:text-white [.group:not([data-selected])_&]:hidden">
                  <CheckIcon aria-hidden="true" className="h-5 w-5" />
                </span>
              </ListboxOption>
            ))
          ) : (
            <p className="py-2 pl-3 pr-9 text-gray-900">
              No categories available.
            </p>
          )}
        </ListboxOptions>
      </div>
    </Listbox>
  );
}

  • 下拉列表正确获取并显示选项。
  • 选择选项后,返回预期数据,但所选选项未显示在下拉列表的占位符中,他始终显示“选择类别”文本。
mysql reactjs laravel api
1个回答
0
投票

import { useState, useEffect } from "react";
import { Listbox, ListboxButton, ListboxOption, ListboxOptions } from "@headlessui/react";
import { CheckIcon, ChevronDownIcon } from "@heroicons/react/20/solid";
import { HiOutlineUserGroup } from "react-icons/hi2";

function SelectCategory({ onChange, value }) {
  const [categoryData, setCategoryData] = useState([]);
  const [selectedCategory, setSelectedCategory] = useState(null); // Initially no category selected

  useEffect(() => {
    setCategoryData([
      {
        category: "Category1",
        id: 1
      },
      {
        category: "Category2",
        id: 2
      }
    ]);
  }, []);

  const handleCategoryChange = (category) => {
    console.log("Selected Category:", category); // Debugging line
    setSelectedCategory(category);
  };

  return (
    <Listbox value={selectedCategory} onChange={handleCategoryChange}>
      <ListboxButton className="relative w-full h-[5vw] border-x-[0.1vw] cursor-default text-center text-gray-900 hover:ring-1 hover:ring-inset hover:ring-gray-300 focus:outline-none">
        <span className="mx-[0.5vw] border-b-[0.1vw] flex justify-between">
          <div className="mr-[0.7vw]">
            <HiOutlineUserGroup className="text-black h-[1.7vw] w-[1.7vw]" />
          </div>
          <label className="font-semibold mr-[0.7vw] text-[1.5vw]">Category</label>
          <div>
            <ChevronDownIcon aria-hidden="true" className="h-[2vw] w-[2vw] text-gray-800" />
          </div>
        </span>
        <span>
          <span className="ml-[1vw] text-sm text-gray-500 block truncate">
            {selectedCategory ? selectedCategory.category : "Select a category"}
          </span>
        </span>
      </ListboxButton>

      <ListboxOptions anchor="bottom">
        {categoryData.map((category) => (
          <ListboxOption key={category.id} value={category} className="data-[focus]:bg-blue-100">
            {category.category}
          </ListboxOption>
        ))}
      </ListboxOptions>
    </Listbox>
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.0.0/umd/react-dom.production.min.js"></script>

此代码对我有用,请您检查一次!!

© www.soinside.com 2019 - 2024. All rights reserved.