【问题标题】:this axios api call returns an empty array for the call, but the second one returns a value这个 axios api 调用为调用返回一个空数组,但是第二个返回一个值
【发布时间】:2020-02-05 08:20:46
【问题描述】:

我正在尝试使用下面的上下文从 api 获取数据,然后将其传递给其他组件。数据来自 unsplash,所以我想先使用用户设置的关键字将其过滤掉。但是,该函数返回的第一个数组是空的,但是如果我 console.log() 它,我会按预期得到所有数据

import React, {useState, createContext} from 'react';
import axios from 'axios';

export const ImageContext = createContext();

export const ImageContextProvider = ({children}) => {

const [images, setImages] = useState([]);
const count = 15;
const start = 1;

const getImages = async (keyword) => {
    await axios.get(`api/photos?count=${count}&start=${start}&keyword=${keyword}`)
        .then(res => setImages(res.data.results));

}

return ( 
    <ImageContext.Provider value={{images, getImages: getImages }}>
        {children}
    </ImageContext.Provider>
 );
 }

这是将关键字传递给将用于从 API 获取数据的上下文的组件

 import React, { useState, useContext} from 'react';
  import { ImageContext } from '../../Context/ImageContext';

  export const SearchBar = () => {
      const { getImages, images } = useContext(ImageContext);
      const[keyword, setKeyword] = useState('');

      const searchImages = async (e) => {
      e.preventDefault();
      await getImages(keyword);
      console.log(images);
   }

    return ( 
    <form onSubmit={searchImages}>
        <input type='text' placeholder='Search Images' value={keyword} onChange={(e) => 
        setKeyword(e.target.value)}/>
        <input type='submit'/>
    </form>
 );
 }

【问题讨论】:

  • 每次渲染都会改变状态。当您在 await 语句之后进行 console.log 时,您将不会获得更新的状态。但是,如果您渲染图像,您应该会看到更新
  • @kkesley 谢谢,它有效。我渲染了组件,一切正常

标签: reactjs axios


【解决方案1】:

你快到了:)

由于您使用的是 React 钩子,因此您需要 useEffect 以便能够发送 Http 请求。它相当于`componentDidMount。

如何使用它?
import React, {useState, createContext, useEffect} from 'react';

useEffect(() => {
    const result =  axios.get(`api/photos?count=${count}&start=${start}&keyword=${keyword}`)
        .then(res => setImages(res.data.results));  // remember to update your state


  }, []);  // don't forget to pass an empty array


【讨论】:

  • 谢谢。你能告诉我如何将搜索关键字传递给钩子吗?
【解决方案2】:

看看你的getImages()函数:

const getImages = async (keyword) => {
  await axios.get(`api/photos?...`).then(...);
}

如果我是对的,那是一个错误的结构,因为您正在混合 await 和 then()。此外,您的 getImages() 没有返回值。我认为以下解决了您的问题:

const getImages = async (keyword) => {
  const res = await axios.get(`api/photos?...`);
  setImages(res.data.results);
  return res.data.results;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-01
    • 2013-07-02
    • 2019-04-10
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    相关资源
    最近更新 更多