【问题标题】:trying to fetch data with fetch and promise, doesnt work (react)尝试使用 fetch 和 promise 获取数据,不起作用(反应)
【发布时间】:2021-06-03 12:31:00
【问题描述】:

我正在尝试使用 fetch 从 API 中获取数据,我可以 console.log 将结果记录在 fetch 中,但在 fetch 之外我无法访问数据。

所以我得到了这个包含函数的 fetchData.js 文件:

export const fetchData = (url) => {
    
    return fetch(url)
        .then(response => response.json())
        .then(result => console.log(result))
        .catch(error => console.log('error', error))
}

然后在 app.jsx 文件中我这样调用函数:

import { fetchData } from "./fetchData";

const URL = "https://pokeapi.co/api/v2/pokemon"

function App() {
  let data = fetchData(URL);
  console.log(data);

//return etc

但是 console.log(data) 一直说“未定义”

有人可以帮帮我吗?

【问题讨论】:

  • 你正在调用一个异步函数,然后在检查它的值之前没有等待它返回。
  • 没错,但他应该在日志中看到Promise。尝试删除第二个then,即.then(result => console.log(result))。它正在返回undefined

标签: javascript reactjs api promise fetch


【解决方案1】:

您必须等待异步操作完成才能记录它。

let data = fetchData(URL).then(() => {console.log(data);});

(也可以删除then(result => console.log(result)) 或从中返回结果)

【讨论】:

  • 这会给我一个错误“App.jsx:26 Uncaught TypeError: Cannot read property 'then' of undefined”
【解决方案2】:

fetchData 是一个async 函数,这就是为什么在解析fetchData 之前执行console.log:

export const fetchData = async (url) => {  
    return fetch(url)
        .then(response => response.json())
        .then(result => (result)) //--> data
        .catch(error => console.log('error', error))
}

然后在组件里面,在useEffect里面:

function App() {
  const [data, setData] = useState([]) //--> keep data in component state
  
  useEffect(()=> {
     fetchData(URL) //--> fetch data when component is mounted
      .then(response => setData(response))
  }, []);
  //...
}

【讨论】:

  • 啊是的,这是有效的!唯一奇怪的是,当我将 {data} 放入返回时,它会给出错误但 console.log(data) 正在工作?未捕获的错误:对象作为 React 子项无效(找到:带有键 {devices} 的对象)。如果您打算渲染一组子项,请改用数组。
  • 如何渲染内容?检查数据是否具有您期望的格式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-17
  • 1970-01-01
  • 1970-01-01
  • 2020-07-13
  • 2019-03-18
  • 2020-12-03
相关资源
最近更新 更多