【发布时间】:2020-11-07 23:46:58
【问题描述】:
我正在使用全球捐赠 API 来制作慈善查找器应用程序。
CharityFinderPage.js 组件中有两个下拉菜单和一个搜索按钮。现在点击搜索按钮,我想使用themeId 获取慈善机构。端点是https://api.globalgiving.org/api/public/projectservice/themes/{themeId}/projects
我知道在handleClick 上我应该获取慈善机构,但是我如何在handleClick 的CharityFinderPage.js 组件中获取themeId 的值。
我想要的是在按钮点击时显示一个新的卡片组件,就像显示一张慈善卡片,上面填充了 API 数据中的字段,但首先我需要能够从 API 获取数据,然后我可以渲染一个新组件。
代码如下:
CharityFinderPage.js
const CharityFinderPage = () => {
const handleClick = () => {
console.log("inside handleclick")
}
return (
<div style={containerStyle}>
<h1>Charity Finder ❤️</h1>
<h3>Search for charity</h3>
<h4>
Filter charities by personal search conditions. Use the dropdown below
to see charities matching your criteria.
</h4>
<Themes />
<Regions />
<button onClick={handleClick}>Search</button>
</div>
)
}
export default CharityFinderPage
Themes.js
import React, { useEffect, useState } from "react"
import axios from "axios"
const url = `https://api.globalgiving.org/api/public/projectservice/themes.json?api_key=${process.env.REACT_APP_api_key}`
const Themes = () => {
const [isLoading, setIsLoading] = useState(false)
const [selectValue, setSelectValue] = useState("")
const [themes, setThemes] = useState([])
useEffect(() => {
const fetchThemes = async () => {
try {
setIsLoading(true)
const result = await axios.get(url)
setThemes(result.data.themes.theme)
setIsLoading(false)
} catch (err) {
console.log(err)
}
}
fetchThemes()
}, [])
const handleChange = (event) => {
console.log("inside handleChange", event.target.value)
setSelectValue(event.target.value)
}
return (
<div>
{isLoading ? (
<h4>Loading......</h4>
) : (
<div>
<label>Select theme: </label>
<select onChange={handleChange} value={selectValue}>
{themes.map((theme, id) => {
return <option key={id}>{theme.name}</option> //{id} is the `themeId`
})}
</select>
</div>
)}
</div>
)
}
export default Themes
Regions 组件与Themes 完全相同。
【问题讨论】:
标签: javascript reactjs api react-hooks react-props