You need to enable JavaScript to run this app. React开发股票数据拉取功能时股票代码搜索组件实现问题
优惠活动
大模型
产品
解决方案
定价
更多

React开发股票数据拉取功能时股票代码搜索组件实现问题

股票搜索功能修复方案

核心问题梳理

  • 组件首次加载时search默认是空字符串,会直接触发useEffect请求无效路径/quote/?apikey=xxx,不符合接口参数要求
  • 没有适配股票代码的大写规范,用户输入小写代码时会导致接口匹配失败
  • 缺少请求错误处理逻辑,接口异常时没有反馈
  • API请求地址定义在useEffect外部,存在变量引用时序风险

修复后完整代码

import { useState, useEffect } from 'react';
// 按需引入你用到的AgGridReact、Badge、Button组件

function SearchBar(props) {
  const [innerSearch, setInnerSearch] = useState("");
  return (
    <div>
      <input
        aria-labelledby="search-button"
        name="search"
        id="search"
        type="search"
        value={innerSearch}
        onChange={(e) => setInnerSearch(e.target.value)}
        // 增加回车触发搜索的适配
        onKeyDown={(e) => e.key === 'Enter' && props.onSubmit(innerSearch)}
      />
      <button
        id="search-button"
        type="button"
        onClick={() => props.onSubmit(innerSearch)}
      >
        Search
      </button>
    </div>
  );
}

function Quote() {
  const [search, setSearch] = useState("");
  const [rowData, setRowData] = useState([]);
  // 这里填入你自己的API token
  const API_token = "";

  const columns = [
    { headerName: "Name", field: "name", sortable: true, filter: true },
    { headerName: "Open", field: "open" },
    { headerName: "Low", field: "dayLow" },
    { headerName: "High", field: "dayHigh" },
    { headerName: "Close", field: "previousClose" },
    { headerName: "Volume", field: "volume" },
  ];

  useEffect(() => {
    // 空搜索值不发请求
    if (!search.trim()) return;

    const API_Call = `https://financialmodelingprep.com/api/v3/quote/${search.trim().toUpperCase()}?apikey=${API_token}`;
    fetch(API_Call)
      .then((res) => {
        if (!res.ok) throw new Error('请求失败,请检查股票代码或API权限')
        return res.json()
      })
      .then((data) =>
        data.map((quote) => {
          return {
            name: quote.name,
            open: quote.open,
            dayLow: quote.dayLow,
            dayHigh: quote.dayHigh,
            previousClose: quote.previousClose,
            volume: quote.volume,
          };
        })
      )
      .then((quotes) => setRowData(quotes))
      .catch(err => {
        console.error(err)
        // 这里可以加你自己的错误提示逻辑,比如弹窗提示
        setRowData([])
      });
  }, [search, API_token]);

  return (
    <div className="container">
      <h1>STOCK Quotes</h1>
      <SearchBar onSubmit={(val) => setSearch(val)} />
      <p>
        <Badge colour="success">{rowData.length}</Badge>
        Stock Quotes of Companys
      </p>

      <div
        className="ag-theme-balham"
        style={{
          height: "300px",
          width: "800px",
        }}
      >
        <AgGridReact
          columnDefs={columns}
          rowData={rowData}
          pagination={true}
          paginationPageSize={8}
        />
      </div>
      <Button
        colour="info"
        size="sm"
        className="mt-3"
        target="_blank"
      >
        Go to Open Stock API
      </Button>
    </div>
  );
}

export default Quote;

优化点说明

  • 增加空值判断,避免无效请求
  • 对传入的股票代码自动去除空格、转大写,适配接口规范
  • 增加回车触发搜索的交互,符合用户使用习惯
  • 新增请求错误捕获逻辑,避免接口异常导致页面崩溃
  • 将API请求地址移到useEffect内部,避免变量引用异常

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 06:27:02