如何在redux应用程序中处理react-router路由中的无效ID?

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)

然后messageundefined在情况下,没有这样的消息存在,该组件必须及时处理,并呈现不同的东西.然而,这似乎膨胀组件,我想也许这应该在路由器中处理?如果没有这样的消息,则不应该允许调用该路由.

有什么想法吗?

Mar*_*ock 1

我也对此感兴趣,我有一个解决方案,尽管不是最优雅的解决方案。希望这会有所帮助。

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方法最初被调用并等待回调。调用onEnterPromiseasyncGetMessage并将isFound属性设置为locationtotruefalse

然后getComponent调用,我使用工厂来提供Message组件作为Component. 它需要返回一个回调,并在回调中error返回一个函数state作为第一个参数。从那里它检查isFound属性location并返回Component工厂或NotFound组件中的设置。

我也在设置路线status为 404,以便服务器在渲染第一个页面加载时可以提供正确的 http 代码。

不幸的是, 的签名getComponent没有接收状态,否则可以在那里完成所有操作,而不是使用onEnter太。

希望这可以帮助。