【问题标题】:How to filter an array on click in react?如何在点击时过滤数组?
【发布时间】:2021-11-26 03:45:21
【问题描述】:

所以,基本上,我正在创建一个网站,您可以在其中搜索 Minecraft 被黑客户端。网站上有一个搜索栏,但您必须准确搜索(不同主题哈哈)。基本上点击一个按钮(搜索按钮),然后我想使用搜索词进行过滤,(不是像现在这样自动)我一直在搜索,但找不到方法。

代码->

import CountUp from 'react-countup';
import { Link } from 'react-router-dom';
import '../App.css';

/*Components ->*/
import Client from '../components/client.js'

function App() {

    const [search, setSearch] = React.useState({
        searchname: ''
    });

    **Array containing client data ->** const [client, setClient] = React.useState([
        { safestatus: 'safe-status-green', safe: 'Safe (Verified)', name: 'Impact', price: 'Free', mcversion: '1.11.2 - 1.16.5', type: 'Injected', compat: 'None (Stand alone client)', desc: 'The Impact client is an advanced utility mod for Minecraft, it is packaged with Baritone and includes a large number of useful mods.', screen: 'https://impactclient.net/', download: 'https://impactclient.net/'},
        { safestatus: 'safe-status-green', safe: 'Safe (Verified)', name: 'Future', price: '15€', mcversion: '1.8.9 - 1.14.4', type: 'Injected', compat: 'None (Stand alone client)', desc: 'Vanilla, OptiFine, Forge and Liteloader support, Easy to use account manager, Auto-reconnect mod.', screen: 'https://www.futureclient.net/', download: 'https://www.futureclient.net/'}
        
    ]);

    const updateSearch = (event) => {
        event.persist();
        setSearch((prev) => ({
            ...prev,
            [event.target.name]: event.target.value
          }));
    };
    
  return (
    <body>
        <div className='header'><Link to='/'>Hacked Hub</Link><div className='header-links'><Link to='/about-us'>About Us</Link> | <Link to='/faq'>FAQ</Link></div></div>
        <div className='counter'><CountUp end={16} duration={0.5}></CountUp>+</div>
        <div className='counter-desc'><div className='code'>hacked clients</div> and counting...</div>
        <div className='nxt-tab'>
            <input name='searchname' value={search.searchname} onChange={updateSearch} placeholder='Search'></input>
            <select name='price'>
                <option value='Free'>Free</option>
                <option value='Paid'>Paid</option>
            </select>
            <select name='safe'>
                <option value='Safe'>Safe</option>
                <option value='Probably Safe'>Probably Safe</option>
                <option value='Not Safe'>Not Safe (BE CAREFUL!)</option>
            </select>
            <select name='mcver'>
                <option value='1.8.9'>1.8.9</option>
                <option value='1.12.2'>1.12.2</option>
                <option value='1.16.5'>1.16.5</option>
                <option value='1.17+'>1.17+</option>
            </select>
            <select name='type'>
                <option value='Main'>Injected</option>
                <option value='Side'>Mod</option>
            </select>
            <select name='compatibility'>
                <option value='With Most Other Clients'>With Most Other Clients</option>
                <option value='Stand Alone'>Stand Alone</option>
            </select>
            <div className='client-warning'><div className='safe-status-red'><div className='code'>⚠ WARNING ⚠</div></div> Only download clients you know are <div className='code'>100%</div> safe! If we do find a client that is a <div className='code'>rat / virus / BTC miner</div> we will tag it as <div className='safe-status-red'><div className='code'>UNSAFE IMMEDIATELY</div></div>. The saftey warnings for clients are <div className='code'>MERE RECCOMENDATIONS</div>, please do thorough research before downloading any hacked client that you are not <div className='code'>100%</div> sure is safe. This page is also in <div className='code'>development</div>, meaning features are prone to break! So be careful!!!</div>
            <div className='code'>Sponsored clients</div>
                <h1>None XD</h1>
            <div className='code'>Submitted clients</div>
                {client
                    **Filtering the array then mapping it -> (This i want to do onClick)** .filter((client) => client.name === search.searchname)
                    .map((client, index) => {
                        return (
                            <Client
                                safestatus={client.safestatus}
                                safe={client.safe}
                                name={client.name}
                                price={client.price}
                                mcversion={client.mcversion}
                                type={client.type}
                                compat={client.compat}
                                desc={client.desc}
                                screen={client.screen}
                                download={client.download}
                            />
                        );
                    })}
            </div>
    </body>
  );
}

export default App;

有谁知道我如何在点击时做到这一点?

【问题讨论】:

    标签: javascript reactjs filter


    【解决方案1】:

    使用两个状态;一个用于跟踪文本字段中的值,另一个用于存储搜索词以进行过滤。仅在单击按钮时设置后者

    const [ searchValue, setSearchValue ] = React.useState("")
    const [ searchTerm, setSearchTerm ] = React.useState("")
    
    const filteredClient = React.useMemo(() => {
      if (searchTerm.length > 0) {
        return client.filter(({ name }) => name === searchTerm)
      }
      return client
    }, [ searchTerm, client ])
    

    在你的 JSX 中

    <input
      name="searchname"
      placeholder="Search"
      value={searchValue}
      onChange={e => setSearchValue(e.target.value)}
    />
    
    <!-- snip -->
    
    <button
      type="button"
      onClick={() => setSearchTerm(searchValue)}
    >Search</button>
    
    <!-- snip -->
    
    {filteredClient.map((client, index) => (
      <Client .../>
    ))}
    

    【讨论】:

    • 谢谢!这有效,感谢您提供详细的答案!
    猜你喜欢
    • 1970-01-01
    • 2013-01-17
    • 2015-06-01
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    相关资源
    最近更新 更多