在Redux ajax请求后显示404

时间:2017-06-12 13:45:56

标签: reactjs redux react-router

当用户在我的React / Redux应用程序中导航到 func getFriendChatConversationModel(_ friendID: String) -> ChatConversationModel? { let realm = try! Realm() let chatConversationModels = realm.objects(ChatConversationModel.self).filter("typeIndex = %@", ChatTypes.ChatType.oneToOne.index) var friendChatConversationModel: ChatConversationModel? for chatConversationModel in chatConversationModels { if chatConversationModel.userAcitivities.contains(where: { (chatUserAcitivityModel) -> Bool in chatUserAcitivityModel.userID == friendID }) { friendChatConversationModel = chatConversationModel return friendChatConversationModel } } return nil } 时,会触发ajax调用以从数据库中获取相关地点数据。

虽然这一切都按预期工作,但我不知道如果找不到地方,如何显示404。当用户导航到非路由时,我有404路由设置但是如何使用Redux触发404?

在我的容器组件中,我有:

/places/:slug

和我的行动:

this.props.dispatch(fetchPlace(this.props.match.params.slug))

和我的减速机:

import axios from "axios";

export function fetchPlace(slug) {
  return function(dispatch) {
    dispatch({type: "FETCH_PLACE"});
    axios.get("/server/places/" + slug)
      .then((response) => {
        dispatch({type: "FETCH_PLACE_FULFILLED", payload: response.data})
      })
      .catch((err) => {
        dispatch({type: "FETCH_PLACE_REJECTED", payload: err})
      })
  }
}

我可以在我的reducer中使用另一个名为const reducer = (state={ place: {}, isFetching: false, error: null }, action) => { switch(action.type) { case "FETCH_PLACE" : { return { ...state, isFetching: true } } case "FETCH_PLACE_REJECTED" : { return { ...state, isFetching: false, error: action.payload } } case "FETCH_PLACE_FULFILLED" : { return { ...state, isFetching: false, place: action.payload } } default: return state } } export default reducer 的状态属性,并将其初始化为notFound。然后读取响应数据有效负载并检测是否已返回作业。如果没有,请将false设置为notFound。但是我该如何监听notFound为真并触发404?

1 个答案:

答案 0 :(得分:1)

我建议从fetchPlace操作返回一个承诺并将其捕获到容器中。

返回承诺的行动代码

export function fetchPlace(slug) {
  return function(dispatch) {
    dispatch({type: "FETCH_PLACE"});
      return axios.get("/server/places/" + slug)
      .then((response) => {
        dispatch({type: "FETCH_PLACE_FULFILLED", payload: response.data})
      })
      .catch((err) => {
        dispatch({type: "FETCH_PLACE_REJECTED", payload: err})
     })
  }
}

容器代码(您必须能够访问react-router上下文或历史记录对象)

this.props.dispatch(fetchPlace(this.props.match.params.slug))
.then(() => {})
.catch(() => {
  //Redirect to 404 page using history object from props
  this.props.history.replace(`404`)

  //Redirect to 404 page using context
  this.context.router.history.replace(`404`)
})

另一种方法是检查notFound方法中的componentWillReceiveProps(nextProps)值。