【问题标题】:How do I change the data I'm getting from an API dynamically based on what button I'm clicking?如何根据单击的按钮动态更改从 API 获取的数据?
【发布时间】:2021-11-15 00:23:36
【问题描述】:

我正在创建一个加密应用程序,我想根据我在下拉菜单中单击的货币动态更改所有数据。

这是我用来获取市场图表所有数据的函数

getMarketData = async (currency) => {
try {
  const { data } = await axios.get(
    `https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=${currency}&days=30&interval=daily`
  );

【问题讨论】:

    标签: javascript reactjs api


    【解决方案1】:
    1. 您需要两种状态 - 一种用于保存所选货币,另一种用于保存从 API 返回的数据。

    2. 将处理程序添加到select 元素以侦听更改事件。使用所选选项中的值作为您在 URI 中用于货币的变量。

    3. 当您的数据返回时更新data 状态

    4. 只有当你有数据显示它。

    此示例使用模拟 API 返回一些数据。

    const { useEffect, useState } = React;
    
    // Mock data
    const data = { cz: [1, 3, 5], en: [10, 12, 20], de: [45, 32, 34] };
    
    // Mock API that returns data after a second
    function mockApi(currency) {
      return new Promise((res, rej) => {
       setTimeout(() => res(data[currency]), 1000);
      });
    }
    
    function Example() {
    
      // Two states initialised with an empty array
      // for the data, and an empty string for the currency
      const [ data, setData ] = useState([]);
      const [ currency, setCurrency ] = useState('');
    
      // On the initial render update
      // currency state
      useEffect(() => {
        setCurrency('de');
      }, []);
    
      // When the currency state is updated
      // call the API
      useEffect(() => {
        if (currency) {
          mockApi(currency).then(data => setData(data));
        }
      }, [currency]);
    
      // When a new currency is selected
      // update the currency state with the value
      // from the option
      function handleChange(e) {
        const { value } = e.target;
        setCurrency(value);
      }
    
      // Show the select element and add a change 
      // handler to it. If there's data create a list,
      // otherwise show a loading/error message
      return (
        <div>
          <select onChange={handleChange}>
            <option disabled>Choose currency</option>
            <option value="en" selected={currency === "eu"}>EN</option>
            <option value="de" selected={currency === "de"}>DE</option>
            <option value="cz" selected={currency === "cz"}>CZ</option>
          </select>
          {data.length ? (
            <ul>{data.map(el => <li>{el}</li>)}</ul>
          ) : <div>No data</div>}
        </div>
      );
    };
    
    ReactDOM.render(
      <Example />,
      document.getElementById('react')
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
    <div id="react"></div>

    【讨论】:

    • 我注意到,当我使用 selected 时,它会更新状态,但是当组件首次呈现时,状态为空并且我的数据没有加载
    • 什么数据?您的 API 的重点在于它根据货币提供数据,并且没有选择货币。
    • 我希望默认选择一种货币,然后可以根据选择进行更改
    • 我已经更新了我的答案。基本上 1) 在初始渲染时使用另一种效果来更新货币状态,并在选项中添加selected 条件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 2020-12-17
    • 2020-10-10
    • 2020-02-09
    相关资源
    最近更新 更多