Spring Boot 无法从数据库填充选择列表

yqkkidmi  于 2023-01-30  发布在  Spring
关注(0)|答案(1)|浏览(89)

我是前端应用程序开发的新手,尝试从数据库填充选择列表,但无法使用以下方法设置options(使用类似于**How to populate select dropdown elements with data from API - ReactJS**的方法)

const [options, setOptions] = useState([]);

  useEffect(() => {
    async function fetchData() {
      const results = []

      // Fetch data
      GetWithAuth("/categories")
      .then(res => res.json())
      .then(value  => { 
        value.map(element => {
        // --> the value has data and push them to results variable
          results.push({
            key: element.name,
            value: element.id,
          });
        });
      })

      // --> options cannot be filled with results and just have the following value
      setOptions([
        {key: 'Select a category', value: ''},
        ...results
      ])
    }

    // Trigger the fetch
    fetchData();
  }, []);

下面是返回Promise的服务方法:

export const GetWithAuth = (url) => {
  var request = fetch("/api" + url, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      Authorization: localStorage.getItem("tokenKey"),
    },
  });
  return request;
};

那么,我应该如何从数据库填充我的选择列表呢?上面的代码有什么问题吗?

cotxawn7

cotxawn71#

您应该在“then”函数中更新您的状态,并且您应该使用forEach(因为您没有使用return关键字)而不是使用map函数,但是如果您想使用map函数,那么您可以这样使用它

const [options, setOptions] = useState([]);

  useEffect(() => {
    async function fetchData() {

      // Fetch data
      GetWithAuth("/categories")
      .then(res => res.json())
      .then(value  => { 
        const results = value.map(element => {
        // --> the value has data and push them to results variable
          return {
            key: element.name,
            value: element.id,
          }
        });

      setOptions([
        {key: 'Select a category', value: ''},
        ...results,
      ])
      })

    }

    // Trigger the fetch
    fetchData();
  }, []);

但如果您想使用forEach函数,则可以这样做

const [options, setOptions] = useState([]);

  useEffect(() => {
    async function fetchData() {

      // Fetch data
      GetWithAuth("/categories")
      .then(res => res.json())
      .then(value  => { 
        const results = [];
        value.forEach(element => {
        // --> the value has data and push them to results variable
          results.push({
            key: element.name,
            value: element.id,
          })
        });

      setOptions([
        {key: 'Select a category', value: ''},
        ...results,
      ])
      })
    }

    // Trigger the fetch
    fetchData();
  }, []);

相关问题