[英]How to get helper function returning promise for React hook function
我有以下帶有useState
和useEffect
掛鈎的 React 功能組件:
import React, { useState, useEffect } from 'react';
import { requestInfo } from './helpers/helpers';
const App = () => {
const [people, setPeople] = useState([]);
useEffect(() => {
requestInfo('people', '82')
.then(results => setPeople(results))
}, []);
return (
<p>We have {people.length} people in this game.</p>
);
}
export default App;
在helpers.js
我有這個 function:
export const requestInfo = (resource, quantity) => {
fetch(`https://swapi.dev/api/${resource}/?results=${quantity}`)
.then(response => response.json)
.then(data => data.results)
}
我沒有太多編寫調用 API 的異步函數的經驗,但是我查看了這個網站上的其他問答,在這種情況下我需要讓助手 function 返回一個 promise,然后有調用helper function do something with the outcome of the promise, in this case pass it to the setPeople
hook state setter function.
我目前收到錯誤TypeError: Cannot read property 'then' of undefined
from my call to useEffect
。
我認為端點是正確的,因為此命令在我的終端中運行時有效並返回預期的數據:
curl https://swapi.dev/api/people/\?results\=82
如果有人能告訴我如何修改我的一個或兩個函數以使其工作,我將不勝感激。
一些問題 - 一個在 useEffect 中,您需要等待 requestInfo 調用的響應,因此:
useEffect(() => {
const getAsyncInfo = async () => {
const res = await requestInfo('people', '82')
setPeople(res)
}
getAsyncInfo()
}, [])
接下來確保您從requestInfo
返回 fetch 並且它是json()
作為 function - requestInfo 也可以使用 async/await ,例如:
export const requestInfo = async(resource, quantity) => {
const res = await fetch(`https://swapi.dev/api/${resource}/?results=${quantity}`)
const json = await res.json()
return json.results
}
您的 function requestInfo
當前未返回任何內容(因此出現錯誤消息)。 您要么需要去掉箭頭后的{}
,要么需要return fetch(...).then(...)
等。
export const requestInfo = (resource, quantity) =>
fetch(`https://swapi.dev/api/${resource}/?results=${quantity}`)
.then(response => response.json)
.then(data => data.results)
export const requestInfo = (resource, quantity) => {
return fetch(`https://swapi.dev/api/${resource}/?results=${quantity}`)
.then(response => response.json)
.then(data => data.results)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.