Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

reactjs - Filtering and object in javascript

In my react app i'm coding a small photo gallery, with a GraphQL query i get all the images in a folder in this format:

{
  "data": {
    "allFile": {
      "edges": [
        {
          "node": {
            "childImageSharp": {
              "fluid": {
                "aspectRatio": 0.7518796992481203,
                "originalName": "music_01.jpg"
              }
            }
          }
        },
        {
          "node": {
            "childImageSharp": {
              "fluid": {
                "aspectRatio": 1.3333333333333333,
                "originalName": "music_02.jpg"
              }
            }
          }
        },
        {
          "node": {
            "childImageSharp": {
              "fluid": {
                "aspectRatio": 0.7518796992481203,
                "originalName": "food_01.jpg"
              }
            }
          }
        }
      ]
    }
  },
  "extensions": {}
}

it return about 50 entries, that (using links on the page) i need to filter out, something like a cateogry, where the category name is based on regex /category/ (or with indexOf) (music, foood and so) in the filename. i was thinking to use a state to keep the original data separated from the filtered one, but it looks im not able to filter out the data to keep only the needed one.

my approach was something like

const Portofolio = ({data}) =>{

  const [filtered, setFiltered]=useState();

  function onFilterData(filter) {
    //scroll through data and keep only the entries that match filter
    //assign the kept data to filtered with setFiltered(keptdata)
 }

 return (
    //render the gallery from filtered object
 )
}

but im stuck on the filtered part and i cant get out of it! any suggestion?

question from:https://stackoverflow.com/questions/65926905/filtering-and-object-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use useMemo to save the filtered list and avoid to use useEffect and setState and with this approach you save one render every time that your data changed.

You need something like this:

const filteredList = React.memo(() => {
  return data.filter(({ childImageSharp: { fluid } }) => { 
    return fluid. originalName.indexOf(filter) > -1;
  })
}, [data, filter])

data: is all your items list

filter: is the route that need to match with the item name


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...