最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

搜索查询以过滤React中的结果

运维笔记admin13浏览0评论

搜索查询以过滤React中的结果

搜索查询以过滤React中的结果

我正在尝试基于简单的用户搜索输入来过滤数据。

我不确定是否是我过滤数据的方式,但是每当我在文本框中输入内容时,数据就会消失。我可以在开发工具中看到正在存储查询的状态。

这是我的上下文文件中的代码。我计划在搜索功能修复后添加其他过滤器,因此是使用更复杂代码的原因。

    import * as React from "react";

const DefaultState = {
  cardListings: [],
  filter: {}
};

const CardListingsContext = React.createContext(DefaultState);

export const CardListingsConsumer = CardListingsContext.Consumer;

export class CardListingsProvider extends React.Component {
  static applyFilter(cards, filter) {
    const { query } = filter;
    let result = cards;
    if (query) {
      const search = query.toLowerCase();
      result = result.filter(item => item.title.indexOf(search) !== -1);
    }
    return result;
  }

  state = DefaultState;

  componentDidMount() {
    fetch("http://localhost:9000/mwBase")
      .then(res => res.json())
      .then(res => {
        this.setState({ cardListings: res });
      });
  }

  updateFilter = filter => {
    this.setState({
      filter
    });
  };

  render() {
    const { children } = this.props;
    const { cardListings, filter } = this.state;

    const filteredListings = CardListingsProvider.applyFilter(
      cardListings,
      filter
    );

    return (
      <CardListingsContext.Provider
        value={{
          allListings: cardListings,
          cardListings: filteredListings,
          updateFilter: this.updateFilter
        }}
      >
        {children}
      </CardListingsContext.Provider>
    );
  }
}

这是我的输入表格

<form
      className={formClasses}
      noValidate
      onChange={() =>
        setTimeout(() => this.props.updateFilter(this.state), 0)
      }
    >
      <p className="mb-1">Refine your results</p>
      <div className="form-group">
        <input
          type="text"
          className="form-control form-control-lg"
          placeholder="Search for a card..."
          name="query"
          value={this.state.query}
          onChange={event => this.setState({ query: event.target.value })}
        />
      </div>

以及在我的主页上应用过滤器的位置:

<CardListingsProvider>
          <CardListingsConsumer>
            {function(value) {
              const { cardListings, updateFilter } = value;
              return (
                <>
                  <Filter updateFilter={updateFilter} />
                  <div className="columns">
                    {cardListings.map(item => (
                      <Card key={item.itemId} card={item} />
                    ))}
                  </div>
                </>
              );
            }}
          </CardListingsConsumer>
        </CardListingsProvider>
              </div>

这里是我的数据集的示例:

   [
{
itemId: [
"120901386991"
],
title: [
"1952 Topps Mickey Mantle Chase Card Box 18 packs 5 1950s or 1960's cards per box"
],
globalId: [
"EBAY-US"
],
subtitle: [
"3 BX LOT. 1 VINTAGE PK PER 25 BOXES* LOOK 4 1952 MANTLE"
],
primaryCategory: [
{
categoryId: [
"213"
],
categoryName: [
"Baseball Cards"
]
}
],
secondaryCategory: [
{
categoryId: [
"156521"
],
categoryName: [
"Vintage Non-Sport Cards"
]
}
],
galleryURL: [
".jpg"
],
viewItemURL: [
";toolid=10044&campid=5338164673&customid=watchbask&lgeo=1&vectorid=229466&item=120901386991"
],
paymentMethod: [
"PayPal"
],
autoPay: [
"true"
],
location: [
"USA"
],
country: [
"US"
],
shippingInfo: [
{
shippingServiceCost: [
{
@currencyId: "USD",
__value__: "0.0"
}
],
shippingType: [
"Free"
],
shipToLocations: [
"Worldwide"
],
expeditedShipping: [
"false"
],
oneDayShippingAvailable: [
"false"
],
handlingTime: [
"1"
]
}
],
sellingStatus: [
{
currentPrice: [
{
@currencyId: "USD",
__value__: "118.0"
}
],
convertedCurrentPrice: [
{
@currencyId: "USD",
__value__: "118.0"
}
],
sellingState: [
"Active"
],
timeLeft: [
"P10DT14H59M31S"
]
}
],
listingInfo: [
{
bestOfferEnabled: [
"false"
],
buyItNowAvailable: [
"false"
],
startTime: [
"2012-04-23T16:52:17.000Z"
],
endTime: [
"2019-10-23T16:52:17.000Z"
],
listingType: [
"FixedPrice"
],
gift: [
"false"
],
watchCount: [
"443"
]
}
],
returnsAccepted: [
"false"
],
condition: [
{
conditionId: [
"1000"
],
conditionDisplayName: [
"Brand New"
]
}
],
isMultiVariationListing: [
"false"
],
pictureURLLarge: [
"==/z/sT8AAOSw62VZv9qQ/$_1.JPG"
],
topRatedListing: [
"false"
]
},
回答如下:

看起来您发布的代码段可能不完整。我在提供程序组件中看到applyFilter函数的一些不平衡括号。

  static applyFilter(cards, filter) {
    const { query } = filter;
    let result = cards;
    if (query) {
      const search = query.toLowerCase();
      result = result.filter(item => item.title.indexOf(search) !== -1);
    }

  state = DefaultState;

[我也想知道为什么您需要setTimeout才能调用setState组件中的Filter函数。以下

onChange={() =>
          setTimeout(() => this.props.updateFilter(this.state), 0)
        }

您也可以摆脱它。

我进行了一些编辑以完成applyFilter功能,以返回过滤后的数据。请查看下面的代码和Run Code Snippet,以查看运行中的代码。希望这会有所帮助!

// Provider Class

const DefaultState = {
  cardListings: [],
  filter: {}
};

const CardListingsContext = React.createContext(DefaultState);

const CardListingsConsumer = CardListingsContext.Consumer;

class CardListingsProvider extends React.Component {
  static applyFilter(cards, filter) {
    const {
      query
    } = filter;
    let result = cards;
    if (query) {
      const search = query.toLowerCase();
      result = result.filter(item => item.title.indexOf(search) !== -1);
    }
    return result;
  }

  state = DefaultState;

  componentDidMount() {
    Promise.resolve([{
        id: 1,
        title: "animation"
      },
      {
        id: 2,
        title: "balloon"
      },
      {
        id: 3,
        title: "cartoon"
      }
    ]).then(res => {
      this.setState({
        cardListings: res
      });
    });
  }

  updateFilter = filter => {
    this.setState({
      filter
    });
  };

  render() {
    const {
      children
    } = this.props;
    const {
      cardListings,
      filter
    } = this.state;

    const filteredListings = CardListingsProvider.applyFilter(
      cardListings,
      filter
    );

    return ( <
      CardListingsContext.Provider value = {
        {
          allListings: cardListings,
          cardListings: filteredListings,
          updateFilter: this.updateFilter
        }
      } >
      {
        children
      } 
      </CardListingsContext.Provider>
    );
  }
}



class Filter extends React.Component {
  state = { query: "" };
  render() {
    return (
      <form
        noValidate
        onChange={() =>
          setTimeout(() => this.props.updateFilter(this.state), 0)
        }
      >
        <p className="mb-1">Refine your results</p>
        <div className="form-group">
          <input
            type="text"
            className="form-control form-control-lg"
            placeholder="Search for a card..."
            name="query"
            value={this.state.query}
            onChange={event => this.setState({ query: event.target.value })}
          />
        </div>
      </form>
    );
  }
}




class Home extends React.Component {
  render() {
    return (
      <div>
        <CardListingsProvider>
          <CardListingsConsumer>
            {function(value) {
              const { cardListings, updateFilter } = value;
              return (
                  <React.Fragment>
                  <Filter updateFilter={updateFilter} />
                  <div className="columns">
                    {cardListings.map(item => (
                      <div key={item.itemId}>{JSON.stringify(item)}</div>
                    ))}
                  </div>
                  </React.Fragment>
              );
            }}
          </CardListingsConsumer>
        </CardListingsProvider>
      </div>
    );
  }
}





ReactDOM.render( <Home /> , document.getElementById("root"))
<script src="https://cdnjs.cloudflare/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>
发布评论

评论列表(0)

  1. 暂无评论