在React中,如何在获取数据后进行数据筛选?

huangapple go评论70阅读模式
英文:

How to filter data after data is fetched in React?

问题

// 如果语句没有起作用

import { useState, useEffect } from 'react';

const Fetch = () => {
    const [data, setData] = useState();
    const [currency, setCurrency] = useState('crypto');
    const [isLoaded, setIsLoaded] = useState(false);

    useEffect(() => {
        fetch('https://api.coingecko.com/api/v3/exchange_rates')
            .then((res) => { return res.json() })
            .then((res) => { setData(res.rates); setIsLoaded(true); console.log(res); })
    }, [])

    if (!isLoaded) {
        return <h2>等待数据...</h2>
    } else {
        return (
            <div>
                <label htmlFor="currency">选择货币 </label>
                <select id='currency' onChange={(e) => setCurrency(e.target.value)}>
                    <option value="all">所有</option>
                    <option value="crypto">加密货币</option>
                    <option value="fiat">法定货币</option>
                    <option value="commodity">大宗商品</option>
                </select>

                {Object.values(data).map((item, i) => {
                    return (
                        <div key={i}>
                            <h3>{item.name}({item.unit}) <span style={{ color: "red" }}>{item.value}</span></h3>
                            <p>类型 {item.type} </p>
                            <hr />
                        </div>
                    )
                })}
            </div>
        )
    }
}

export default Fetch;
英文:

I'm new in React. I'm try to filter data after this data will received.
I have select tag with options and I want to change data array after select will changed.
For example if selected option will have value 'crypto' show array only with type 'crypto'
Thanks for answer

import { useState, useEffect } from &#39;react&#39;
const Fetch = () =&gt; {
const [data, setData] = useState();
const [currency, setCurrency] = useState(&#39;crypto&#39;);
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() =&gt; {
fetch(&#39;https://api.coingecko.com/api/v3/exchange_rates&#39;)
.then((res) =&gt; { return res.json() })
.then((res) =&gt; { setData(res.rates); setIsLoaded(true); console.log(res); })
}, [])
if (!isLoaded) {
return &lt;h2&gt;Waiting for data...&lt;/h2&gt;
} else {
return (
&lt;div&gt;
&lt;label htmlFor=&quot;currency&quot;&gt;Choose currency: &lt;/label&gt;
&lt;select id=&#39;currency&#39; onChange={setCurrency}&gt;
&lt;option value=&quot;all&quot;&gt;All&lt;/option&gt;
&lt;option value=&quot;crypto&quot;&gt;Crypto&lt;/option&gt;
&lt;option value=&quot;fiat&quot;&gt;Fiat&lt;/option&gt;
&lt;option value=&quot;commodity&quot;&gt;Commodity&lt;/option&gt;
&lt;/select&gt;
{Object.values(data).map((item, i) =&gt; {
return (
&lt;div key={i}&gt;
&lt;h3&gt;{item.name}({item.unit}) : &lt;span style={{ color: &quot;red&quot; }}&gt;{item.value}&lt;/span&gt;&lt;/h3&gt;
&lt;p&gt;type: {item.type} &lt;/p&gt;
&lt;hr /&gt;
&lt;/div&gt;
)
})}
&lt;/div&gt;
)
}
}
export default Fetch;

If statement not working

答案1

得分: 0

要在JavaScript中过滤数据,您可以使用filter函数:

Object.values(data)
      .filter(item => item?.type === currency)
      .map(...)

传递一个您选择的函数,该函数对数组中的每个值返回truefalse

如果您想要更多细节,可以在文档中找到

英文:

To filter data in JavaScript, you may use the filter function:

Object.values(data)
.filter(item =&gt; item?.type === currency)
.map(...)

Pass a function of your choice that returns either true or false for each value in the array.

If you want more details, you can find them in the docs.

答案2

得分: 0

首先,你需要修复你的 onChange 处理程序,它应该返回一个 React ChangeEvent。目前你把状态设置为了事件本身,而不是选定的值。为此,你还需要添加一个 value 属性,将选择元素变为一个 受控输入

&lt;select
  id=&quot;currency&quot;
  onChange={() =&gt; setCurrency(e.target.value)}
  value={currency}
&gt;
  ...
&lt;/select&gt;

对于筛选,你可以使用 filter

{
  Object.values(data)
    .filter((item) =&gt; item.type === currency)
    .map((item, i) =&gt; {
      return (
        &lt;div key={i}&gt;
          &lt;h3&gt;
            {item.name}({item.unit}) :{&quot; &quot;}
            &lt;span style={{ color: &quot;red&quot; }}&gt;{item.value}&lt;/span&gt;
          &lt;/h3&gt;
          &lt;p&gt;type: {item.type} &lt;/p&gt;
          &lt;hr /&gt;
        &lt;/div&gt;
      );
    });
}
英文:

First you need to fix your onChange handler this returns a React ChangeEvent. Currently you're setting the state to the event instead of the selected value. For this you'll also need to add a value prop to make the select element a controlled input.

&lt;select
  id=&quot;currency&quot;
  onChange={() =&gt; setCurrency(e.target.value)}
  value={currency}
&gt;
  ...
&lt;/select&gt;

For the filtering you can use filter.

{
  Object.values(data)
    .filter((item) =&gt; item.type === currency)
    .map((item, i) =&gt; {
      return (
        &lt;div key={i}&gt;
          &lt;h3&gt;
            {item.name}({item.unit}) :{&quot; &quot;}
            &lt;span style={{ color: &quot;red&quot; }}&gt;{item.value}&lt;/span&gt;
          &lt;/h3&gt;
          &lt;p&gt;type: {item.type} &lt;/p&gt;
          &lt;hr /&gt;
        &lt;/div&gt;
      );
    });
}

huangapple
  • 本文由 发表于 2023年2月20日 00:12:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75501525.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定