1

I'm new to react/hooks I'm having a bit of trouble getting my head around updating a search on an API based on a user input. I currently have an API that im hitting to get a table of stocks. I then draw this table. I have created some radio buttons that allow the user to click so that it can refine the search on the API. I am passing the value of the selected radio button back to the URL as industrySelection, what I am hoping for is that the table will update from this result but it doesn't do anything. Could someone please explain how to fix this and why?

function StockTable() {
  const [industrySelection, setIndustry] = useState("");
  const [rowData, setRowData] = useState([]);

  const columns = [
    { headerName: "Stock", field: "name"}, 
    { headerName: "Symbol", field: "symbol"}, 
    { headerName: "Industry ", field: "industry"}
  ];


  useEffect(() => {
    fetch(`http:PRIVATE/stocks/symbols/${industrySelection}`)
    .then(res => res.json())
    .then(data => 
      data.map(stocks => {
        return {
          name: stocks.name,
          symbol: stocks.symbol,
          industry: stocks.industry,
        };
      })
    )
    .then(stocks => setRowData(stocks));
  }, []);

  return (
/* Place Search Options and grab users choice */
    <div className = "userSelect">
      {
        industryChoices.map(feature => (
            <ul className = "radioULlist"> 
              <li className = "radioList">
                <input type="radio" name="radioButton" value = {feature}  
                  onChange={event => {
                    const { value } = event.target;
                    setIndustry(value);
                  }}
                />
                <label className = "radioLabel">{feature}</label>
              </li>
            </ul>
      ))}
    </div>
/* DRAW TABLE HERE */
  );
}
4

2 回答 2

1

具有空依赖数组的钩子是 的同义词componentDidMount,它只在组件挂载时运行一次。具有填充依赖数组的钩子更像是componentDidUpdate,当数组中的值更新(浅比较)时,调用钩子的回调。

添加industrySelection到效果的依赖数组。当值发生industrySelection变化时,效果会触发并最终更新rowData

useEffect(() => {
  fetch(`http:PRIVATE/stocks/symbols/${industrySelection}`)
  .then(res => res.json())
  .then(data => 
    data.map(stocks => {
      return {
        name: stocks.name,
        symbol: stocks.symbol,
        industry: stocks.industry,
      };
    })
  )
  .then(stocks => setRowData(stocks));
}, [industrySelection]);
于 2020-04-15T07:22:35.043 回答
1

将您的 useEffect 的最后一行更改为:

}, []);

}, [industrySelection]);

这样每次更改行业选择时都会调用 useEffect

于 2020-04-15T07:22:54.757 回答