[英]How to handle invalid ID in react-router route in a redux app?
我有路由/messages/:id
呈現一條消息。 但是,如果id
指向不存在的消息,則應在何處以及如何處理? 我的組件使用redux綁定到消息:
function mapStateToProps(state, ownProps) {
return {
message: state.messages[ownProps.params.id]
}
}
如果不存在這樣的消息,並且組件必須處理該消息並呈現不同的內容,則該message
將是undefined
。 但是,這似乎會使組件膨脹,我認為這應該在路由器中處理嗎? 如果沒有這樣的消息,則不應允許調用路由。
有什么想法嗎?
我也對此感興趣,盡管沒有最優雅的解決方案,但我有一個解決方案。 希望這會有所幫助。
import NotFound from './NotFound'
import Message from './Message'
import {asyncGetMessage} from './api'
const onEnter = ({params, location}, replaceState, callback) => {
asyncGetMessage(params.messageId)
.then((isFound) => {
location.isFound = isFound
callback()
})
}
const getComponent = (Component) => {
return (location, callback) => {
callback(null, (state) => {
if (location.isFound) {
state.route.status = 200
return <Component {...state} />
} else {
state.route.status = 404
return <NotFound {...state} />
}
})
}
}
const routes = (
<Route path='messages'>
<Route path=':messageId' getComponent={getComponent(Message)} onEnter={onEnter} />
</Route>
)
這里發生的是最初調用onEnter
方法並等待回調。 onEnter
調用asyncGetMessage
promise並將location
的isFound
屬性設置為true
或false
。
然后調用getComponent
,我使用了一個工廠來提供Message
組件作為Component
。 它需要返回一個回調,並且在回調中包含error
和一個以state
作為第一個參數的函數。 從那里檢查location
的isFound
屬性,並返回工廠中的Component
設置或NotFound
組件。
我還將路由status
設置為404,以便服務器在呈現第一頁加載時可以提供正確的http代碼。
不幸的是, getComponent
的簽名不接收狀態,否則可以在此完成所有操作,而不用使用onEnter
。
希望這可以幫助。
我遇到了同樣的問題,但是我對此的最終想法是,這與路由器或getComponent包裝器無關,而僅與組件自身處理其自身的(故障)狀態有關。
當您的組件能夠以錯誤狀態掛載時,例如message = undefined,則您的組件應根據錯誤狀態做出反應。
也可以選擇防止Component處於錯誤狀態,但這仍然會使您的代碼this腫,並且Component仍然無法處理其錯誤狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.