按类别过滤JSON结果-React Hooks [英] Filtering JSON results in categories - React Hooks

查看:54
本文介绍了按类别过滤JSON结果-React Hooks的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说明

创建一个允许用户使用的网络界面:

Create a web interface that allows a user:

根据特定条件过滤玩家列表.这些是您将根据测试数据创建的搜索过滤器:

To filter a list of players based on specific criteria. These are the search filters you will be creating based on the test data:

年龄:允许用户过滤特定年龄或年龄范围(例如7、5-9、15-17等)中的玩家

Age: allow the user to filter for players within a specific age or age range (e.g. 7, 5-9, 15-17, etc.)

性别:允许用户根据其指定的性别过滤玩家

Gender: allow the user to filter for players based on their specified gender

状态:允许用户根据他们来自可用测试数据中所处的状态来过滤玩家

State: allow the user to filter for players based on the state they reside in from available test data

状态:允许用户根据其状态(有效/无效)来过滤玩家

Status: allow the user to filter for players based on their status (active/inactive)

您可以应用多个过滤器来缩小搜索结果的范围.

You can apply more than one filter to narrow down your search results.

编辑任何播放器的信息.

To edit the information of any player.

代码

我正在尝试使用React Hooks,只是想对我正在做的事情有几点了解.

I'm trying to use React Hooks, just wanting a few points of clarity on what I'm doing.

1)我想知道每个变量的初始状态是否有意义.另外,在useEffect方法上,只需要运行一次即可使用axios来获取数据,这就是需要的所有内容吗?

1) I'm wondering if my initial state for each variable makes sense. Also, on the useEffect method, that just needs to be run once to fetch the data with axios and that's all that is needed correct?

2)仅需要4个单独的函数来处理每个条件.我是否只需要通过对象数组进行 map 映射并 filter 所需的结果?

2) Just need 4 separate functions that handle each criteria. Would I just need to map through the array of objects and filter the wanted results?

import React, { useEffect, useState } from 'react';
import axios from 'axios';


const App = () => {

const url = "https://dii-test.s3.amazonaws.com/players.json";

const [age, setAge]         = useState([]);
const [gender, setGender]   = useState([]);
const [state, setState]     = useState('');
const [status, setStatus]   = useState(false);

useEffect(() => {
  axios.get(url).then(json => setAge(json.data))
}, []);

const renderTable = () => {
  return age.map(user => {
    return (
      <tr>
       <td>{user.age}</td>
      </tr>
     )
    })
}

 return (
  <div className="App">
    <tbody>{renderTable()}</tbody>
  </div>
 );
}



export default App;

推荐答案

我将为玩家提供一个状态对象,然后为另一个(或多个)状态对象跟踪过滤器.像这样:

I'd have a single state object for the players and then another (or multiple) to keep track of the filters. Something like:

  const [genderFilter, setGenderFilter] = useState(null)
  const [players, setPlayers] = useState([])

然后,您可以一口气过滤它们-在players数组的 filter 内进行一系列测试,或者如果发现链接,则在一系列的 filters 中进行过滤更具可读性和性能:

Then you can filter them in one fell swoop - either a series of tests inside a filter of the players array, or in a series of filters if you find chaining more readable and performant:

  return (
    <table>
      <tbody>
        {players.map(player => {
          // After all the filters are run, map the players to table rows
          return (
            <tr>
              <td>{player.name}</td>
              <td>{player.age}</td>
              <td>{player.state}</td>
              <td>{player.gender}</td>
              <td>{player.status}</td>
            </tr>
          )
        }).filter(player => {
          // genderFilter can be "male", "female", or null
          return genderFilter ? player.gender === genderFilter : true
        }).filter(player => {
          // ageFilter is an object with min & max
          return player.age >= ageFilter.min && player.age <= ageFilter.max
        }).filter(player => {
          // stateFilter can be a string or null
          return stateFilter ? player.state == stateFilter : true
        }).filter(player => {
          // statusFilter can be "active" or "inactive"
          return statusFilter === player.status
        })}
      </tbody>
    </table>
  )

这是快速,肮脏和丑陋的版本,目的只是为了说明逻辑.如果过滤器最终删除了所有播放器,在axios呼叫期间为用户等待/加载消息等,则显然不包括任何显示/消息.

That's the quick, dirty, and ugly version just to show the logic. It obviously doesn't include any displays/messages if the filters end up removing all players, waiting/loading message for the user during the axios call, etc.

这也仅适用于中小型数据集-如果您必须在客户端下载并过滤成千上万个结果,则速度会很慢,并且最好为用户提供将数据发送到服务器的服务.查询并仅返回适当的结果.

And this is also only for a small to medium sized data set - if you have to download and filter thousands of results on the client side, it will be slow and your user would be better served sending the data to the server to query and return just the appropriate results.

这篇关于按类别过滤JSON结果-React Hooks的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆