您好,每當對資料庫呼叫更新時,我都會嘗試從資料庫中呈現更新的內容。我找到了這個解決方案,但現在我的“add”方法與鏈接問題中的“fetch”方法不在同一個檔案中。我嘗試了以下方法,但仍然無法正常作業:
檔案1:(回傳方法將UploadedImages通過映射它們來呈現)
const [UploadedImages,setUploadedImages] = useState([])
const fetchUserAllPhotos = async () => {
const res = await client.get('/get-photos')
setUploadedImages(res.data.photoList)
}
useEffect(()=>{
fetchUserAllPhotos()
},[])
檔案 2:
import {fetchUserAllPhotos} from './Gallery/AllPhotos';
const addNewPhoto = async () => {
if (success) {
await fetchUserAllPhotos()
}
}
但是,在檔案 1 的回傳(渲染)方法中,每當添加新照片時,它都不會給出更新的結果(我需要注銷并重新登錄才能看到更改)。我該如何解決呢?
如果函式被包裹在另一個函式中怎么辦?
export default function PhotoGrid(props){
const [UploadedImages,setUploadedImages] = useState([])
const fetchUserAllPhotos = async () => {
const res = await client.get('/get-photos')
setUploadedImages(res.data.photoList)
}
useEffect(()=>{
fetchUserAllPhotos()
},[])
}
uj5u.com熱心網友回復:
您需要在 file1 的底部添加這一行
export {fetchUserAllPhotos}
一般來說,每次你想要匯入函式、陣列、物件等時,它應該如下所示:
檔案1:
const func = () => {
//implementaion of the function
}
export {func}
檔案2:
import {func} from './file1' //you need to give the path of file1
func() //now you can use the fanction everywhere in file2
注意:您可以根據需要匯出任意數量的函式,請注意在匯出和匯入中使用相同的名稱很重要
export {func1, func2, func3, obj1, abj2, arr1, arr2}
如果要從 react 組件匯出函式,則需要在組件外部定義函式
const func = () => {
}
export default function MyReactComponent(prop) {
//implementation of your component
}
export {func}
如果您需要在函式內使用組件的道具,您可以將此道具作為函式引數傳遞。
我建議避免從 React 組件中匯出函式,因為當你的專案變得更大時,你會開始沮喪地發現你是否隱含了每個幻想。相反,最好的做法是添加一個新的 js 檔案,你在那里實作所有 fetches 函式,我通常將此檔案稱為 api.js 這個檔案應該看起來像這樣(我從我的專案中獲取了這段代碼,我使用 axios 來制作獲取到服務器):
import axios from "axios"
const url = 'http://localhost:8080'
const api = {
getQuestions : async () => {
return axios.get(`${url}/question/all`)
},
getQuestionById : async (id) => {
return axios.get(`${url}/question/${id}`)
}
}
export default api;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/451755.html
標籤:javascript 反应 反应式 异步
