首页 > 解决方案 > React js搜索不适用于graphql分页

问题描述

我使用react js创建了一个搜索函数来过滤从 graphql 端点 代码中获取的数据表:

const SearchRes = () => {
    let filtredRes = data.Orders.edges
        .filter(item => item.node.shippingAddress.name === (query));

    let res = filtredRes.length === 0 ? data.Orders.edges : filtredRes;                                         
    return res;
}

然后只需执行以下操作即可获取数据:

SearchRes.map(...)

这很好用,我可以进行搜索,但是当我实现graphql 分页时,搜索停止了对结果的工作,它只在单击按钮以获得更多结果之前工作

代码 :

import React, { useState, useEffect } from 'react'
import { gql, useQuery } from '@apollo/client';
import Table  from 'react-bootstrap/Table'
import Moment from 'react-moment';
import moment from "moment";
import { Link } from 'react-router-dom';
import Row from 'react-bootstrap/Row'
import Col from 'react-bootstrap/Col'
import { DangerousChangeType } from 'graphql';
import Search from './Search'
import Button from 'react-bootstrap/Button'

const GET_All_Orders = gql`
query Orders($input1: PaginationInput) {
    Orders(input: $input1){
     pageInfo {
       hasNextPage
       hasPreviousPage
     }
     edges{
       cursor
       node {
          id
          closed
          email
          createdAt
          updatedAt
          cancelledAt
          displayFinancialStatus
          displayFulfillmentStatus
          lineItems{
            edges{
              node {
                customAttributes{
                  key
                  value
                }
                id
                quantity
                title
                variant{
                  id
                  image {
                    altText
                    id
                    src
                  }
                  title
                  weight
                  weightUnit
                  price
                }
              }
            }
          }
          shippingAddress { 
            name
          }
         phone
         subtotalPrice
         totalPrice
         totalRefunded
         totalTax
         processedAt
       }
     }
   }
 }
`;


export default function AllOrders({ input1 }) {
    const { loading, error, data  , fetchMore} = useQuery(
        GET_All_Orders,
        {
            variables: {
                "input1": {
                    "num": 20,
                }
            },
        }
    );
    let date = new Date();
    const [query, setQuery] = useState('');

    if (loading) return <h4>読み込み中...</h4>;
    if (error) return `Error! ${error}`;
    
    const SearchRes = () => {
        let filtredRes = data.Orders.edges
            .filter(
                item => (
                    item.node.shippingAddress.name === (query) ||
                    item.node.email === (query)
                )
            );                                     
        let res = filtredRes.length === 0 ? data.Orders.edges : filtredRes;                                      
        return res;
    }

    return (
        <div>
           <Row > 
    <Col xs={10}> <h5>すべての注文</h5></Col>
    <Col><h5>  日付 : <Moment format="YYYY/MM/DD">
     
 { date}
            </Moment> </h5></Col>
  </Row>
   
 <br/>
 <Search getQuery={(q) => setQuery(q)} />
 <br/>
 <Table responsive hover size="sm">
  <thead>
    <tr>
    
    <th className="allOrders">注文日&lt;/th>
    <th className="allOrders">名前</th>
    <th className="allOrders">注文者メールアドレス</th>
    <th className="allOrders" >配送状態&lt;/th>
    <th className="allOrders" >支払状況</th>
      <th className="allOrders" >合計金額</th>
      <th className="allOrders" >詳細</th>
 
    </tr>
  </thead>
  <tbody>
 {SearchRes().map(({ edges ,node :{id , createdAt , displayFulfillmentStatus , displayFinancialStatus , totalPrice , email , shippingAddress: { 
            name
          } }}) => (
    
    
    <tr key={id}>
      
  
      <td>    <Moment format="YYYY/MM/DD">
       {createdAt}
            </Moment></td>
            <td>{ name} </td>  
      <td>{ email} </td>

      {displayFulfillmentStatus == "FULFILLED" ? <td className="success">配送済み&lt;/td> :  <td className="failed">未配送&lt;/td>}
    
 
 
 
       
      {displayFinancialStatus == "PAID" ? <td>支払済み</td> : <td>未払い&lt;/td> }
      <td>{totalPrice} </td>
      <td>  
      <Link to={`/orders/${id}`} className="btn btn-light">
      詳細
          </Link></td>
   
    </tr>
    
    

  ))}
  </tbody>
</Table>
    
            {/* button responsible for the pagination */}
            <div className="text-center">
                <Button
                    variant="light"
                    onClick={() => {
                        fetchMore({
                            variables: {
                                "input1": {
                                    "num": 20,
                                    "cursor": data.Orders.edges[data.Orders.edges.length - 1].cursor
                                }
                            },
                            updateQuery: (prevResult, { fetchMoreResult }) => {
                                fetchMoreResult.Orders.edges = [
                                    ...prevResult.Orders.edges,
                                    ...fetchMoreResult.Orders.edges
                                ];
                                return fetchMoreResult;
                            }
                        });
                    }}
                >
                    もっと
                </Button>
            </div>
        </div>
    );
}

也许问题是:

1)我认为问题是因为按钮获取不同的表,也许这就是函数不搜索它的原因。

  1. 可能是因为num 变量,因为它就像 graphql 中的第一个参数,你应该指定你应该得到多少结果,所以当我在按钮中写 "num": 20时,它总是返回前 20 个结果而不是后面的结果光标

标签: reactjsgraphqljsxcreate-react-appreact-apollo

解决方案


我认为SearchRes功能应该是

const SearchRes = () => {
    let filtredRes = data.Orders.edges
        .filter(item => item.node.shippingAddress.name === (query) ||
                    item.node.email === (query));

    let res = query ? filtredRes : data.Orders.edges;                                         
    return res;
}

当查询为空时,即用户让搜索输入为空,应显示所有结果,当用户在搜索输入中输入内容时,即使没有匹配的内容,也只显示过滤后的结果。我不知道这是否是您的错误的真正原因,但我认为这确实是一个错误。


推荐阅读