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

React从外部API取数后,下拉选择无法渲染详情列表问题

问题分析与修复方案

你的代码里有三个核心问题导致选中下拉选项后无法渲染对应内容:

1. useEffect无限触发请求

你的useEffect没有添加依赖数组,会导致组件每次渲染都重新执行fetch请求,既浪费资源还可能引发状态频繁更新。给useEffect加一个空数组依赖,让它只在组件挂载时执行一次:

useEffect(() => {
  fetch('https://api.n.exchange/en/api/v1/currency/')
    .then(response => response.json())
    .then(data => setOption(data))
}, []) // 空数组依赖,仅组件首次挂载时执行

2. 事件处理函数不能直接返回JSX渲染

handleClick作为onChange的事件处理函数,它返回的JSX不会自动渲染到页面上。你需要新增一个状态来存储选中的货币信息,然后在组件的return部分根据这个状态渲染内容:

const [selectedCurrency, setSelectedCurrency] = useState(null)

3. forEach无法生成可渲染元素

forEach没有返回值,所以{selectedBase.forEach(...)}不会输出任何可渲染的JSX。改用map方法,它会返回新的元素数组,刚好适配React的列表渲染逻辑。


修复后的完整代码

import { useEffect, useState } from "react"

function Data() {
    const [options, setOption] = useState([])
    // 新增状态存储选中的货币详情
    const [selectedCurrency, setSelectedCurrency] = useState(null)

    useEffect(() => {
        fetch('https://api.n.exchange/en/api/v1/currency/')
            .then(response => response.json())
            .then(data => setOption(data))
    }, []) // 添加空依赖数组,避免无限请求

    function handleClick(event) {
        // 用find代替filter,因为货币code唯一,直接返回单个匹配对象更高效
        const selected = options.find(item => item.code === event.target.value)
        setSelectedCurrency(selected)
    }

    return(
        <div>
            <select onChange={handleClick}>
                <option selected="true" hidden={true}>选择一种货币</option>
                {
                    options.map(option =>
                        <option key={option.code} value={option.code}>{option.code}</option>
                    )
                }
            </select>
            {/* 根据选中状态渲染对应信息 */}
            {selectedCurrency && (
                <ul>
                    <li>货币名称:{selectedCurrency.name}</li>
                    <li>货币代码:{selectedCurrency.code}</li>
                    {/* 可按需添加更多展示字段,比如精度、符号等 */}
                </ul>
            )}
        </div>
    )
}

export default Data

额外优化说明

  • 用find替代filter:由于每个货币的code是唯一的,find直接返回匹配的单个对象,比filter返回数组更高效,后续处理也更简洁。
  • 修正option属性:原代码中select属性拼写错误,改为标准的selected。
  • 添加根元素包裹:用div包裹select和列表,保证React组件返回单个根元素的规范,也方便后续扩展布局。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:30:22