phi*_*ilk 6 javascript reactjs redux
我有一条/messages/:id
呈现消息的路线.但是,如果id
指向不存在的消息,应该在何处以及如何处理?我的组件使用redux绑定到消息:
function mapStateToProps(state, ownProps) {
return {
message: state.messages[ownProps.params.id]
}
}
Run Code Online (Sandbox Code Playgroud)
然后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>
)
Run Code Online (Sandbox Code Playgroud)
这里发生的是该onEnter
方法最初被调用并等待回调。调用onEnter
PromiseasyncGetMessage
并将isFound
属性设置为location
totrue
或false
。
然后getComponent
调用,我使用工厂来提供Message
组件作为Component
. 它需要返回一个回调,并在回调中error
返回一个函数state
作为第一个参数。从那里它检查isFound
属性location
并返回Component
工厂或NotFound
组件中的设置。
我也在设置路线status
为 404,以便服务器在渲染第一个页面加载时可以提供正确的 http 代码。
不幸的是, 的签名getComponent
没有接收状态,否则可以在那里完成所有操作,而不是使用onEnter
太。
希望这可以帮助。
归档时间: |
|
查看次数: |
715 次 |
最近记录: |