【问题标题】:Loader while filtering data with keywords加载器同时使用关键字过滤数据
【发布时间】:2021-07-05 06:14:03
【问题描述】:

当我使用过滤器方法搜索属性时,我想显示一个加载器。当有人搜索时,它应该在过滤器完成时显示加载微调器,它应该显示数据。我没有使用 API 调用过滤数据。我已经使用反应钩子来加载状态,默认情况下它是真的。如果有人可以帮助我如何在函数中使用 setState 钩子来更改状态,如果我在函数中使用 setState 它将一次又一次地重新渲染,这是不允许的。如果你们中的任何人都可以帮助,请帮助

export const applyFilters = (properties, query) => {
  return (
    properties &&
    properties.filter((property, i) => {
      let matches = true;

      if (query) {
        const keys = ["title"];
        let containsQuery = false;

        keys.forEach(key => {
          if (property[key].toLowerCase().includes(query.toLowerCase())) {
            containsQuery = true;
          }
        });

        if (!containsQuery) {
          matches = false;
        }
      }

      return matches;
    })
  );
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

【问题讨论】:

    标签: reactjs react-hooks next.js


    【解决方案1】:

    您的过滤是一个同步操作,因此它应该几乎是瞬时的。我根本不会展示微调器。

    一般我建议过滤器本身应该是一个状态。那将是您的 query 变量。但过滤后的数据应该只是从queryproperties 的状态(或道具)派生的变量。

    export const FilterProperties = () => {
      const [query, setQuery] = useState("");
      // some state that gets set somehow, or maybe properties is a prop
      const [properties, setProperties] = useState([]);
    
      const filteredProperties = applyFilters(properties, query);
    
      return (
        <div>
          <input value={query} onChange={(e) => setQuery(e.target.value)} />
          <ul>
            {filteredProperties.map((property) => (
              <li key={property.id}>{property.title}</li>
            ))}
          </ul>
        </div>
      );
    };
    

    如果您担心性能问题,那么您可以使用useMemo 仅在queryproperties 发生变化时重新计算filteredProperties 变量。

    const filteredProperties = useMemo(
      () => applyFilters(properties, query), 
      [properties, query]
    );
    

    过滤器功能本身可以清理很多。我们可以使用默认参数而不是检查 propertiesquery 是否存在。我们可以为properties 使用一个空数组来返回不匹配项,并为query 使用一个空字符串来匹配所有内容。

    如果您总是只想搜索title,那么这个keys 数组毫无意义:

    const applyFilters = (properties = [], query = "") =>
        properties.filter((property) =>
            property.title.toLowerCase().includes(query.toLowerCase())
        );
    

    但我们可以将keys 设为参数以允许更多自定义。我们使用Array.prototype.some() 方法来查看是否有任何键匹配。

    const applyFilters = (properties = [], query = "", keys = ["title"]) =>
        properties.filter((property) =>
            // true if any key contains the query
            keys.some((key) =>
                property[key].toLowerCase().includes(query.toLowerCase())
            )
        );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 2016-11-20
      • 1970-01-01
      • 2018-04-05
      相关资源
      最近更新 更多