React Search Bar - 每次搜索后运行两次

React Search Bar - runs twice after each search

我正在尝试在 React 中实现搜索栏,但我需要一些帮助。我的功能部分起作用:D

点击提交后函数运行两次。第一次获取所有数据,然后获取过滤后的数据。我不知道我错过了什么。如果你能帮上忙,我欠你很多!

感谢您的宝贵时间和帮助!

import React, {useState} from 'react'
import { useQuery, gql } from '@apollo/client'
import {Link} from "react-router-dom";

const search_reviews= gql`
 query SearchReviews ($my_query: String) {
    reviews (filters: {title: {contains: $my_query} }) {
      data{
        id
        attributes{
          title
          rating
          body
          categories{
            data{
              id
              attributes
              {
                name
              }
            }
          }
        }
    }
  
 }
}

`


export default function Test() {

    const [ query, setQuery] = useState("")
    const { loading, error, data } = useQuery(search_reviews, {variables: {my_query: query}})
    if (loading) return <p>Loading data...</p>
    if (error) return <p>Error fetching data</p>
    console.log(data)

    return (
        <div>
            <div className="ui search">
                <div className="ui icon input">
                    <form onSubmit={e => {
                        e.preventDefault()
                        console.log(e.target[0].value)
                        setQuery(e.target[0].value)
                        e.preventDefault()
                    }}>
                        <input type="text"
                               placeholder="Search IP"
                               className="prompt"
                                />
                        <button type="submit">Submit</button>
                    </form>
                </div>
            </div>

            {data.length !== 0 && (
            <div className="dataResult">
                    {data.reviews.data.map(review => (
                        <div key={review.id} className="review-card">
                        <div className="rating">{review.attributes.rating}</div>
                        <h2>{review.attributes.title}</h2>

                        {review.attributes.categories.data.map(c => (
                            <small key={c.id}>{c.attributes.name}</small>
                            ))}

                            <p>{review.attributes.body.substring(0, 200)}... </p>
                            <Link to={`/details/${review.id}`}>Read more</Link>
                            </div>
                            ))}

            </div>
                )}
        </div>
    )
}


const { loading, error, data } = useMemo(() => {
   if(!query) return {loading: false, error: false, data: [] }


   return useQuery(search_reviews, {variables: {my_query: query}})

}, [query]);

这个有用吗?

当您的组件呈现查询为空字符串时,您会获取所有数据,在您点击提交后,查询会得到更新(状态得到更新),因此会发生重新呈现,现在查询不为空,因此您会得到过滤后的数据

基本上您需要的是仅在查询实际发生变化时调用 useQuery,您可以使用 Effect(但这需要对当前代码进行一些更改)

成功了!

const { loading, error, data } = useQuery(search_reviews, {skip: !first,variables: {my_query: query}})