[英]API inside child dynamic component doesn't fetch data
我有一個 api (photoFetch),它獲取一個 JSON,其中包含來自在線 JSONplaceholder 的照片數據。 它位於我的子組件內部,即基於id的動態組件(父組件是我的主頁)
userPhotoPage.js(子組件)
export const UserPhotoPage = async ({match}) => {
const [data, setData] = useState("");
const photoFetch = await fetch('https://jsonplaceholder.typicode.com/photos')
.then(res => res.json())
.then(result => setData(data.albums))
.catch(error => console.log("error"))
const userPhoto = photoFetch.find((userPhoto) =>{
return parseInt(match.params.id) == userPhoto.id
})
return <>
{match.isExact && <>
<h1>{userPhoto.title}</h1>
<p>image = {userPhoto.url}</p>
</>}
</>
}
我還嘗試將其包裝在 try catch 語句中,但沒有任何效果。 它不獲取數據,我總是得到一個“(TypeError):無法讀取未定義的屬性'find'”,因為我的const userPhoto沒有從photoFetch.find((userPhoto)獲取任何數據。我是REACT的新手所以我真的不知道如何着手解決這個問題。已經研究了一段時間了。
我能夠在我的父組件(主頁)上使用用戶 JSON 獲取數據,並且我使用了非常相似的方法。 我正在嘗試為我的子組件重新創建它,但它不起作用。 這是它在主頁上的樣子。 (我只在這里發布一段代碼,頂部)
homePage.js(父組件,只是一個例子)
class homePage extends Component {
constructor(props) {
super(props);
this.state = {
users: [],
isLoading: false,
search: ""
};
}
async componentDidMount() {
this.setState({isLoading: true});
await fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(result => this.setState({users: result}))
.catch(error => console.log("error"))
}
再次感謝堆棧溢出幫助像我這樣的菜鳥!
當您執行const photoFetch = await (...)
您的代碼等待獲取 promise 的結果並使用它設置 const 的值。 但是,您的 promise 沒有返回任何內容,因為最后一個.then()
的主體執行了一個 void 操作,該操作只是通過調用setData(...)
來更改鈎子“數據”的值。 這就是為什么您的錯誤顯示無法讀取未定義的屬性“查找””:photoFind 那時沒有分配值。
您應該在最后一個 .then .then()
的箭頭 function 中返回一個值,以便將該值設置為常量。 (我不知道你正在使用的 API 所以我不確定這個值應該是什么。也許你的 userPhoto 正試圖在你的鈎子中搜索一個名為 data 的值?)
PD:我還建議您記住在獲取結果或在主頁的方法ComponentDidMount
中捕獲錯誤時再次將isLoading
的值設置為 false!
首先,您不能在功能組件主體中直接獲取請求,而是必須使用useEffect
鈎子。
其次,您可以簡單地請求/photos/:id
最后,返回的數據是一個數組,不包含專輯鍵
你的代碼看起來像
export const UserPhotoPage = async ({match}) => {
const [data, setData] = useState("");
useEffect(() => {
await fetch(`https://jsonplaceholder.typicode.com/photos/${match.params.id}`)
.then(res => res.json())
.then(result => setData(result))
.catch(error => console.log("error"))
}, [match.params.id])
return <>
{match.isExact && <>
<h1>{data.title}</h1>
<p>image = {data.url}</p>
</>}
</>
}
React 在 16.8 版本中引入了可以在我們的功能組件中使用的鈎子,我們有一個名為useEffect
的鈎子來調用 apis 或我們曾經在componentDidMount
或componentWillMount
中調用的任何異步調用。 所以你的子組件看起來像這樣。 當我們使用async-await
時,我們也不需要.then
。
export const UserPhotoPage = async ({match}) => {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/photos')
.then(res => res.json())
.then(result => {
setData(data.albums)
})
.catch(error => console.log("error"))
}
const userPhoto = photoFetch.find((userPhoto) =>{
return parseInt(match.params.id) == userPhoto.id
})
return (<>
{match.isExact && <>
<h1>{userPhoto.title}</h1>
<p>image = {userPhoto.url}</p>
</>}
</>)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.