首页 > 解决方案 > Semantic UI React:无法从 REST API 中获取下拉列表的值

问题描述

我正在尝试使用 Semantic UI React 的下拉元素。它旨在与允许获取电影列表的 REST API 一起使用。React 被配置为从适当的 REST API 应用程序中获取数据(这已经适用于前端的其他元素)。

我想获取电影名称列表作为选项。请看下面的 JS 片段。

import React, { useState, useEffect } from "react";
import { Dropdown } from "semantic-ui-react";

export const MovieDropdown = () => {
  const [movie, setMovie] = useState("");
  const [movieOptions, setMovieOptions] = useState([]);

  useEffect(() => {
    fetch("/movies")
      .then((response) => response.json())
      .then((data) =>
        setMovieOptions(
          data.map((x) => {
            return { key: x.name, text: x.name, value: x.name };
          })
        )
      );
  }, []);

  return (
    <Dropdown
      placeholder="Select Movie"
      search
      selection
      options={movieOptions}
      onChange={(e) => setMovie(e.target.value)}
    />
  );
};
export default MovieDropdown;

我无法从https://react.semantic-ui.com/modules/dropdown/#usage-remote弄清楚。

标签: javascriptreactjssemantic-ui-react

解决方案


你的代码看起来不错。改变一个小东西,它会工作:

onChange={e => setMovie(e.target.value)} // you cannot use event in setState. furthermore checkout the second param of the onChange-Event

onChange={(e, {value}) => setMovie(value)}

结帐修复反应警告合成事件在设置状态

这是完整的工作代码

import React, { useState, useEffect } from "react";
import { Dropdown } from "semantic-ui-react";

export const MovieDropdown = () => {
  const [movie, setMovie] = useState("");
  const [movieOptions, setMovieOptions] = useState([]);

  useEffect(() => {
    fetch("/movies")
      .then((response) => response.json())
      .then((data) =>
        setMovieOptions(
          data.map((x) => {
            return { key: x.name, text: x.name, value: x.name };
          })
        )
      );
  }, []);

  return (
    <Dropdown
      placeholder="Select Movie"
      search
      selection
      options={movieOptions}
      onChange={(e, {value}) => setMovie(value)}
    />
  );
};
export default MovieDropdown;

推荐阅读