You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何遍历两个数组并将对应数据渲染到同一表格

你的代码有几个核心问题导致无法正常渲染对应股票代码:

  1. React的状态是不可变的,你直接用push修改symbolArray和dataArray不会触发组件重渲染,页面永远不会展示新添加的数据。
  2. 你在渲染Symbol列时又遍历了整个symbolArray,而实际上dataArray和symbolArray是按搜索顺序一一对应的,直接用当前遍历dataArray的索引取对应位置的symbolArray元素即可。
  3. fetch是异步请求,你同时调用getData和addingStuff会出现时序问题:可能股票代码已经加到数组里了,但API请求还没返回,或者请求失败,最终两个数组长度不一致,索引对应错乱。

最优修改方案

建议直接把股票代码和对应的行情数据合并存在同一个数组里,不需要维护两个独立状态,彻底避免索引不匹配的问题。修改后的完整代码如下:

import { useState } from 'react'

const Quotes = ()=> {
  // 定义输入框状态(原有代码漏了这个状态定义)
  const [input, setInput] = useState('')
  // 单个数组存储:每个元素包含股票代码symbol + 对应行情数据
  const [stockList, setStockList] = useState([])

  // 搜索按钮点击触发逻辑
  const handleSearch = async () => {
    if (!input.trim()) return
    // 拼接接口请求地址,将用户输入的股票代码传入API
    const url = `你的股票API请求地址?ticker=${input.trim()}`
    try {
      const res = await fetch(url)
      const data = await res.json()
      // 状态更新必须传入新数组,不能直接修改原状态
      setStockList(prev => [
        ...prev,
        {
          symbol: input.trim(),
          quote: data
        }
      ])
      // 搜索完成清空输入框
      setInput('')
    } catch (e) {
      console.error('股票行情查询失败:', e)
    }
  }

  return (
    <>
      {/* 股票搜索区域 */}
      <div className="input-group">
        <input 
          id="searchBar" 
          type="search" 
          className="form-control rounded search-bar" 
          placeholder="Enter Ticker Symbol" 
          aria-label="Search" 
          aria-describedby="search-addon" 
          value={input} 
          onInput={e => setInput(e.target.value)} 
        />
        <button 
          type="button" 
          className="searchButton btn p-2 bg-succ" 
          id="searchButton" 
          onClick={handleSearch}
        >
          Quote This Stock
        </button>
      </div>
      {/* 表格区域 */}
      <table className='table'>
        <thead>
          <tr>
            <th scope='col'>Symbol</th>
            <th scope='col'>Current Price</th>
            <th scope='col'>Price Change</th>
            <th scope='col'>Percentage Change</th>
            <th scope='col'>Day High</th>
            <th scope='col'>Day Low</th>
            <th scope='col'>Open Price</th>
            <th scope='col'>Previous Close</th>
          </tr>
        </thead>
        <tbody>
          {stockList.map((item, index) => {
            const {c, d, dp, h, l, o, pc} = item.quote;
            return (
              <tr key={index}>
                <th scope='row'>{item.symbol}</th>
                <td>{c}</td>
                <td>{d}</td>
                <td>{dp}</td>
                <td>{h}</td>
                <td>{l}</td>
                <td>{o}</td>
                <td>{pc}</td>
              </tr>
            )
          })}
        </tbody>
      </table>
    </>
  )
}

最小改动方案

如果你不想修改原有两个数组的存储结构,只需要修改以下三处即可:

  1. 修正状态更新的写法,不能直接对状态变量用push,必须调用set方法传入新数组
  2. 渲染Symbol列时直接用当前索引取对应股票代码,不要遍历整个symbolArray
// getData方法修改
function getData() {
  fetch(url)
    .then(res => res.json())
    .then(data =>{
      setDataArray(prev => [...prev, data])
    })
}
// addingStuff方法修改
const addingStuff = ()=> {
  setSymbolArray(prev => [...prev, input.trim()])
}

// 表格Symbol列渲染修改
<th scope='row'>{symbolArray[index]}</th>

注:原有代码的表头顺序和渲染字段顺序不匹配,上面的完整方案已经做了对应调整,避免字段和表头展示错乱的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:24:08