所以我有一個函式,fillSidebarData(),它為我收集和構建資料,完成后就回傳它。我想要做的是將變數“sidebarData”設定為該函式的回傳值。作為參考,資料如下所示,如果這很重要:
SidebarData = [
{
title: 'Overview',
path: '/overview',
subNav: [
{
title: 'Users',
path: '/users',
},
{
title: 'Revenue',
path: '/revenue',
}
]
}
這是創建資料的函式的代碼。
const [sidebarData, setSidebarData] = useState([])
function fillSidebarData () {
let sidebarData = []
UserService.getPosts(0).then((response) => {
response.data.map((value, key) => {
UserService.getPosts(value.PostID).then((response) => {
let subNav = []
response.data.map((value, key) => {
subNav.push({
title : value.postName,
path: `/${value.PostID}`
})
})
let sidebarItem = {
title: value.postName,
path: `/${value.PostID}`,
subNav : subNav
}
sidebarData.push(sidebarItem)
})
})
//The console log shows the data in the exact format I want it, so nothing weird here
console.log(sidebarData)
return sidebarData
}, error => {
console.log(error)
})
}
useEffect(() => {
//Here is where I want to set the sidebar data to the return value of fillSideBarData method but sidebarData is undefined when using it elsewhere in the code.
setSidebarData(fillSidebarData())
return () => {
setSidebarData([])
}
}, [sidebarData])
uj5u.com熱心網友回復:
因為您的問題缺乏一些背景關系,我將根據我的假設回答您的問題,即您正在嘗試從后端獲取導航資料并根據您獲取的資料呈現導航組件。
我在這里注意到useEffect函陣列件中沒有使用鉤子。根據 React 檔案,您可以使用Effect Hook在函陣列件中執行副作用。
要回答您的原始問題,您setSidebarData需要在fillSidebarData函式內呼叫。
const Nav = () => {
const [sidebarData, setSidebarData] = useState([])
const fillSidebarData = () => {
let sidebarData = []
UserService.getPosts(0).then((response) => {
response.data.map((value, key) => {
UserService.getPosts(value.PostID).then((response) => {
let subNav = []
response.data.map((value, key) => {
subNav.push({
title : value.postName,
path: `/${value.PostID}`
})
})
let sidebarItem = {
title: value.postName,
path: `/${value.PostID}`,
subNav: subNav
}
sidebarData.push(sidebarItem)
})
})
// Your setSidebarData needs to be called here
setSidebarData(sidebarData)
})
.catch(error => {
console.log(error)
})
}
useEffect(() => {
// If you are updating your menu data just once, you probably do not need to resubscribe to your sidebarData state.
fillSidebarData()
})
return (
...
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/354519.html
標籤:javascript 反应 使用状态
