在react中呈现来自外部API的列表



我试图呈现用户点击的一些信息。用户将看到一个代码列表,当点击他们只是得到额外的信息。

让我们从头开始。

所以首先我使用useStateHook来初始化选项。然后我从外部API获取一些数据,将数据转换为JSON格式并更新选项。然后,我将存储在每个选项中的数据映射到一个选项标记中,并在一个select标记中返回这些选项。然后,我将一个事件处理程序添加到名为handleClick的选择标记。然后我使用过滤器来获得特定的选项。问题是,当我试图显示信息,但它不是显示。我试图console.log它,它工作完美,但当我试图在一个列表中显示它没有出现。

下面是我的代码:
import { useEffect,useState } from "react"
function Data() {
//Intializing Options using the useState Hook
const [options , setOption] = useState([])
useEffect(() => {
//Fetching the data
fetch('https://api.n.exchange/en/api/v1/currency/')
.then(response => response.json())
.then(data =>
setOption(data)
)
})
function handleClick(event) {
const selectedBase = options.filter(code =>
code.code === event.target.value
)
return(
<ul>
{selectedBase.forEach(currency => <li>{currency.name}</li>)}
</ul>

)
}
return(
<select onChange={handleClick}>
<option select="true" hidden={true}>Select an Currency</option>
{
options.map(options =>
<option key={options.code} value={options.code}>{options.code}</option>
)
}
</select>
)
}
export default Data

最好创建一个状态来存储选中的选项

const [optionSelected, setOptionSelected] = useState(0)

然后修改句柄更改为只设置状态选项选中而不返回jsx,如下所示:

function handleClick(){
const selectedBase = options.filter(code =>
code.code === event.target.value
)
setOptionSelected(selectedBase)
}

在您的组件返回jsx的原因不显示,因为您没有存储您的选择选项后的值,修改如下:

<>
<select onChange={handleClick} value={optionSelected}>
<option select="true" hidden={true}>Select an Currency</option>
{
options.map(options =>
<option key={options.code} value={options.code}>{options.code}   
</option>
)
}
</select>
<ul>
//your mapping data from optionSelectedState
</ul>
</>

最新更新