我有一個 Home 組件,其中包含 2 個硬編碼的路由和 2 個映射的路由,我正在將計劃物件決議為 Plan 組件。
<Routes>
<Route path='/' element={<Heading>index</Heading>}/>
<Route path='/profile' element={<Profile />}/>
{user &&
user.workoutPlans.map((plan, index) => (
plan._id && <Route path={'/' plan._id} key={index} element={<Plan plan={plan} />} />
))}
</Routes>
計劃組件顯示計劃標題并包含一個部分,它將天陣列映射到 DayCards
<Heading size='2xl' mr={-3}>{plan.title}</Heading>
<Flex direction='column'>
{plan.days.map((day, index) => (
day._id && <DayCard planId={plan._id} day={day} key={index} />
))}
</Flex>
如果我重繪 然后轉到路線 app.com/plan1id 我得到正確的日期串列 [day1, day2, day3, day4, day5] 標題:Plan1
如果我重繪 然后轉到路線 app.com/plan2id 我得到正確的日期串列 [other1, other2, other3] Heading: Plan2
但是,如果我然后從 app.com/plan2id 轉到 app.com/plan1id,我會得到一個混亂的日期串列 [other1, other2, other3, day4, day5] 標題:Plan1
它以相反的順序相同
但是,如果我重繪 然后轉到路線 app.com/plan1id 然后轉到 app.com/profile 然后轉到 app.com/plan2id 它可以正常作業,回傳 [other1, other2, other3] Heading: Plan2
應用程式狀態始終保持不變,據我所知,計劃資料被正確決議,因為 plan.title 始終正確顯示
任何關于為什么會發生這種情況的想法將不勝感激
uj5u.com熱心網友回復:
不要將陣列索參考作 React 鍵。
切換計劃時,路線會發生變化,但Plan組件仍處于掛載狀態,只有planprop 值會更新。這會觸發重新渲染。但是由于這些天使用陣列索引作為 React 鍵,因此鍵不會改變值。計劃“A”中的第 2 天索引等于“B”計劃中的第 2 天索引。
相反,您應該使用被映射資料固有的值。GUID 是很棒的 React 鍵。我建議使用day._id作為 React 鍵,假設這些是唯一的。
<Flex direction='column'>
{plan.days
.filter(day => day._id)
.map((day) => <DayCard planId={plan._id} day={day} key={day._id} />)
}
</Flex>
也可以為Plan組件更正路由代碼。
<Routes>
<Route path='/' element={<Heading>index</Heading>} />
<Route path='/profile' element={<Profile />} />
{user?.workoutPlans
.filter(plan => plan._id)
.map((plan) => (
<Route
path={`/${plan._id}`}
key={plan._id}
element={<Plan plan={plan} />}
/>
))
}
</Routes>
uj5u.com熱心網友回復:
你試過把它關掉嗎
uj5u.com熱心網友回復:
您還應該在 Route 中使用精確的道具,<Heading>否則當您導航到/profile其他路線時,Heading 將首先被呼叫。
有關更多參考,請查看此鏈接https://stackoverflow.com/a/49162423/4554623
<Routes>
<Route exact path='/' element={<Heading>index</Heading>} />
<Route path='/profile' element={<Profile />} />
{user?.workoutPlans
.filter(plan => plan._id)
.map((plan) => (
<Route
path={`/${plan._id}`}
key={plan._id}
element={<Plan plan={plan} />}
/>
))
}
</Routes>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/461113.html
標籤:javascript 反应 反应路由器dom
