【问题标题】:How to get array from function with axios.get in React?如何在 React 中使用 axios.get 从函数中获取数组?
【发布时间】:2023-01-12 20:22:05
【问题描述】:

我有这个功能,从 php 获取数组

function Images(){
  const [state, setState] = useState([]);
   useEffect(() => {
    const url = 'http://work.eniso.ru/galleryready.php'
    axios.get(url).then(response => response.data)
    .then((images, id) => {
      setState({ data: images, id: id })
     })
    }
   )
   console.log(state)
   return state
}

我需要为获取元素数组编写返回 之后我需要在我的类 App React 中使用这个数组

尝试映射作为回报,但可能不对

【问题讨论】:

    标签: javascript reactjs arrays axios


    【解决方案1】:

    嘿,看完你的问题后我得出了结论,即

    要从 axios get 方法获取 Obj 数组,您可以先简单地设置您的状态,然后像这样

    function Images(){
     const [state, setState] = useState([]);
     useEffect(() => {
     const url = 'http://work.eniso.ru/galleryready.php'
     axios.get(url).then(response => setState([...response.data]));
     },[/* please add dependency to aboid unnecessary api calls]);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-29
      • 2020-11-27
      • 1970-01-01
      • 2020-09-14
      • 2022-09-29
      相关资源
      最近更新 更多