How to handle an invalid identifier in a reaction-router route in a redux application?

I have a route /messages/:idthat displays a message. However, if it idindicates a message that does not exist, where and how should it be handled? My component is related to the message using redux:

function mapStateToProps(state, ownProps) {
  return {
    message: state.messages[ownProps.params.id]
  }
}

Then it messagewill be undefinedin the event that such a message does not exist, and the component must process it, and do something else. However, it seems like this is inflating the component, and I think that maybe this should be handled in the router? If there is no such message, it should not allow the called route.

Any thoughts?

+4
source share
2

, , . , .

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 isFound location true false.

getComponent, factory Message Component. error state . isFound location Component factory, NotFound.

status 404, http-, .

, getComponent , onEnter .

, .

+1

, , getComponent Wrapper, () .

, message = undefined, .

, , .

0

Source: https://habr.com/ru/post/1626840/


All Articles