【发布时间】:2020-08-10 12:14:07
【问题描述】:
编辑:您的解决方案有效,但现在我的下拉列表不显示选择的内容,除非选择两次,如下所示:
Here I selected Health Care, but the dropdown still says "Select Industry"
我有一个下拉菜单,我可以从中选择一个选项,它将选项保存到一个变量中。我想使用这个变量来更改我的 useEffect 挂钩中使用的获取路由,以便将找到的数据过滤到特定行业。我该怎么做?有没有更简单的方法来过滤映射数据而不是更改提取地址?
这是我的代码:
import React, {useState, useEffect} from "react";
import { AgGridReact } from "ag-grid-react";
import { Dropdown } from "semantic-ui-react";
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-balham.css";
// Data Table
export default function Table() {
const[rowData, setRowData] = useState([]);
const columns = [
{ headerName: "Name", field: "name", sortable: true},
{ headerName: "Symbol", field: "symbol", sortable: true},
{ headerName: "Industry", field: "industry", sortable: true},
];
const searchIndustry = (event, {value}) => {
let industryChoice = value;
// I want to use this variable
console.log(industryChoice);
}
const DropdownSearchSelection = () => (
<Dropdown
placeholder="Select Industry"
search
selection
options={industryOptions}
onChange={searchIndustry}
/>
);
useEffect(() => {
// To change this address
fetch(`http://131.181.190.87:3000/stocks/symbols${industryChoice}`)
.then(res => res.json())
.then(data =>
data.map(stock => {
return {
name: stock.name,
symbol: stock.symbol,
industry: stock.industry,
};
})
)
.then(stock => setRowData(stock));
}, []);
const industryOptions = [
{ key: "as", value: "", text: "View All Industries" },
{ key: "dc", value: "?industry=consumer%20discretionary", text: "Consumer Discretionary" },
{ key: "ds", value: "?industry=consumer%20staples", text: "Consumer Staples" },
{ key: "en", value: "?industry=energy", text: "Energy" },
{ key: "fi", value: "?industry=einancials", text: "Financials" },
{ key: "hc", value: "?industry=health%20care", text: "Health Care" },
{ key: "in", value: "?industry=industrials", text: "Industrials" },
{ key: "it", value: "?industry=information%20technology", text: "Information Technology" },
{ key: "ma", value: "?industry=materials", text: "Materials" },
{ key: "re", value: "?industry=real%20estate", text: "Real Estate" },
{ key: "ts", value: "?industry=telecommunication%20services", text: "Telecommunication Services" },
{ key: "ut", value: "?industry=utilities", text: "Utilities" },
];
return (
<div className="filter">
<div>
<input type="text" id="searchBox" placeholder="Filter..."/>
<DropdownSearchSelection />
<br/>
</div>
<div className="ag-theme-balham" >
<AgGridReact
columnDefs={columns}
rowData={rowData}
pagination={true}
paginationPageSize={11}
/>
</div>
</div>
);
}
感谢您的帮助! :)
【问题讨论】:
-
我会为每个下拉列表 onChange 调用
setState,然后将状态包含在useEffect的依赖项数组列表中。另外我可能会使用query-string包来解析查询字符串,这样代码会更干净。
标签: javascript reactjs api filtering use-effect