【问题标题】:Fetching the charities using the global giving API using react使用 react 使用全局捐赠 API 获取慈善机构
【发布时间】:2020-11-07 23:46:58
【问题描述】:

我正在使用全球捐赠 API 来制作慈善查找器应用程序。

CharityFinderPage.js 组件中有两个下拉菜单和一个搜索按钮。现在点击搜索按钮,我想使用themeId 获取慈善机构。端点是https://api.globalgiving.org/api/public/projectservice/themes/{themeId}/projects

我知道在handleClick 上我应该获取慈善机构,但是我如何在handleClickCharityFinderPage.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


    【解决方案1】:

    所以你需要在这里做的事情叫做提升状态。

    您需要将主题组件的状态移动到 CharityFinder 组件

    我只提升 selectedValue,因为这就是你所需要的

    CharityFinderPage.js

    const CharityFinderPage = () => {
    
      const [selectValue, setSelectValue] = useState("")
    
    
    
      const handleClick = () => {
        console.log(`inside handleclick with ${selectValue}`)
      }
    
      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>
    
    // you can pass the setSelectValue as prop to Themes component
          <Themes setSelectValue={setSelectValue} selectValue={selectValue} />
          <Regions />
          <button onClick={handleClick}>Search</button>
        </div>
      )
    }
    
    export default CharityFinderPage
    

    主题.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 = ({ selectValue, setSelectValue }) => {
      const [isLoading, setIsLoading] = useState(false)
      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
    

    【讨论】:

    • 您可以在官方文档reactjs.org/docs/lifting-state-up.html了解更多信息
    • 它说selectValue 未定义,在Themes 这一行value={selectValue}&gt; 的组件中。也说props is not defined
    【解决方案2】:

    你可以这样做。

    const CharityFinderPage = () => {
      const [themeId, setThemeId] = useState();
      const handleClick = () => {
        console.log("inside handleclick")
        // make call to endpoint with themeId
      }
    
      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 setThemeId={setThemeId} />
          <Regions />
          <button onClick={handleClick}>Search</button>
        </div>
      )
    }
    
    export default CharityFinderPage
    

    然后在 Themes.js 中:

    ...
    
    const handleChange = (event) => {
      console.log("inside handleChange", event.target.value)
      props.setThemeId(event.target.value);
      setSelectValue(event.target.value)
    }
    
    ...
    

    【讨论】:

      猜你喜欢
      • 2021-04-25
      • 1970-01-01
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      • 2011-03-10
      • 2016-12-09
      • 2016-02-05
      • 1970-01-01
      相关资源
      最近更新 更多