【问题标题】:How do I use a variable from a Const in a useEffect hook? React JS如何在 useEffect 挂钩中使用 Const 中的变量?反应 JS
【发布时间】:2020-08-10 12:14:07
【问题描述】:

编辑:您的解决方案有效,但现在我的下拉列表不显示选择的内容,除非选择两次,如下所示:

Here I selected Health Care, but the dropdown still says "Select Industry"

The here I selected Health Care for a second time and it now shows that it is selected, this is happening with all of the dropdown options


我有一个下拉菜单,我可以从中选择一个选项,它将选项保存到一个变量中。我想使用这个变量来更改我的 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


【解决方案1】:

首先,您需要将来自Dropdown 的选定选项存储到组件的状态中。

const[industryChoice, setIndustryChoice] = useState();

在你的 searchIndustry 方法上,

const searchIndustry = (event, {value}) => {
  setIndustryChoice(value);
}

然后,您将searchIndustry 添加为依赖数组的一部分,它将根据industryChoice 状态获取数据,并且每当industryChoice 的值更新时都会触发。

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));
}, [industryChoice]);

至于您提出的其他问题,您应该将industryChoice 状态的值绑定到Dropdown

<Dropdown
   placeholder="Select Industry"
   search
   selection
   options={industryOptions}
   onChange={searchIndustry}
   value={industryChoice}
/>

【讨论】:

  • 既然这样做了,我的下拉菜单现在不显示选择的内容,除非它选择了两次(我相信是因为 onChange),有什么建议可以解决这个问题吗??
  • 你的意思是每次都要点击两次?
  • 是的,就像页面更改正确,但下拉菜单不会告诉您选择了什么,除非您选择两次,如果这有意义的话。我希望我可以上传视频或其他内容。
  • 我编辑了我原来的问题,所以现在你应该可以看到我的问题的截图了 :)
  • Hmm.. 对于第一个问题,您是否尝试将状态绑定到下拉列表的值?让我在我的答案中包含示例
猜你喜欢
  • 2021-02-13
  • 1970-01-01
  • 2020-01-08
  • 1970-01-01
  • 2019-07-31
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 2019-12-06
相关资源
最近更新 更多