簡體   English   中英

使用反應鈎子更新數組

[英]Updating array using react hooks

我正在使用 Upsplash API 制作應用程序。 渲染后,我想顯示 30 張圖像,女巫工作正常。

import React, { useState, useEffect } from "react"

    const ContextProvider =({ children }) =>{
        const [allPhotos, setAllPhotos] = useState([])
        const [cartItems, setCartItems] = useState([])
        const [imageQuery, setImageQuery] = useState('')
      
        useEffect(() => {
            const url = `https://api.unsplash.com/photos?page=5&per_page=30&client_id=${process.env.REACT_APP_UNSPLASH_KEY}`
    
            async function getPhotos() {
                const photosPromise = await fetch(url)
                const photos = await photosPromise.json()
                setAllPhotos(photos)
            }
            getPhotos()
           
        },[])

然后,我使用我的上下文將 AllPhotos 傳遞給我的 Photos.js,並在 allPhotos 上傳遞 map,將照片傳遞給我的 Image 組件以顯示有關圖像的信息。

 import React, {useContext} from "react"
    import {Context} from "../Context"
    
    
    function Photos(){
        const {allPhotos} = useContext(Context)
    
        const imageElements = allPhotos.map((photo,index) =>(
            <Image key={photo.id}  photo={photo}/>
        ))
        return(
          <>
          <main>
            {imageElements}
          </main>
          </>
        )
    }
    export default Photos




    const Image = ({  photo }) => {
  return (
    <div
      <img src={photo.urls.thumb} className="image-grid" alt="" />
    </div>
    
  )
}

從這里顯示來自 API 的圖像,一切正常。

我現在要做的是添加一個搜索查詢,用戶可以在其中搜索某些圖像。 我為輸入值制作了一個組件

import React, { useContext } from "react"
import {Context} from "../../Context"

const QueryInput = () =>{

    const {imageQuery, setImageQuery, SearchImage} = useContext(Context)
    return(
        <form onSubmit={SearchImage} >
            <label>
                Search Photos
                <input
                type="text"
                className="query-input"
                placeholder="Search Images"
                value={imageQuery}
                onChange={(e) => setImageQuery(e.target.value) }
                />
            </label>
            <button type="submit">Search Image</button>
        </form>
    )
}
export default QueryInput

我在我的上下文中做了一個 searchQuery function

  const SearchImage  = async (e) =>{
           e.preventDefault()
    
        const queryUrl = `https://api.unsplash.com/search/photos? 
         age=5&per_page=30&query=${imageQuery}&client_id=${APP_KEY}`
    
         const response = await fetch(queryUrl)
         const queryPhotos = await response.json();
        
        
        setAllPhotos(prevState => [...prevState, ...queryPhotos])
     
        }

到目前為止一切正常,我可以 console.log(queryPhotos) 並獲取他們搜索的查詢的用戶圖像。 如果我搜索“星星”,我會得到一堆帶有星星的圖像。

我遇到的麻煩是再次映射 allPhotos 並顯示查詢搜索圖像。

我遇到的錯誤是

TypeError:queryPhotos 不可迭代

我已經有一段時間了。 任何信息/建議將不勝感激。 有關代碼的任何問題或需要其他信息,我都可以提供。 謝謝你。

簡而言之。 queryPhotos 不是數組。

unsplash api 對 api /photos/search/photos的響應有點不同。 一個返回數組,另一個是object,需要在results中訪問照片

在此處輸入圖像描述

因此,將這一行從

setAllPhotos(prevState => [...prevState, ...queryPhotos])

setAllPhotos(prevState => [...prevState, ...queryPhotos.results])

應該解決你的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM