javascript - 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弄清楚。
解决方案
你的代码看起来不错。改变一个小东西,它会工作:
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;
推荐阅读
- javascript - 如何使用 React 进行 for 循环以及为什么我的组件没有被渲染
- node.js - MongoDB,按两个数组之间匹配元素的数量对结果进行排序
- nservicebus - Cleint 未收到响应:“找不到消息类型的处理程序”
- angular - 如何在表单外部检查角度输入的有效性而不检查 ng-invalid?
- azure - Azure CLI VHD 上传失败 0.5%
- hyperlink - chainlink 的节点运营商是为交易支付 gas 还是由发起者支付?
- excel - 如何通过 Access VBA 正确访问 Excel 文件
- java - 为什么 jps(java VM lister)会在 cygwin 中给出与 cmd.exe 不同的答案?
- html - 在导航栏 Bootstrap 的右侧对齐图标
- php - mysql:命令不同步;您现在无法运行此命令 -> 在 php 函数中运行查询时