Reactjs Redux ajax请求后显示404
当用户在我的React/Redux应用程序中导航到Reactjs Redux ajax请求后显示404,reactjs,redux,react-router,Reactjs,Redux,React Router,当用户在我的React/Redux应用程序中导航到/places/:slug时,会触发一个ajax调用,以从数据库中获取相关的地点数据 虽然这一切工作如预期,我不知道如何显示404如果没有找到的地方。当用户导航到非路由时,我有一个404路由设置,但是如何使用Redux触发404 在我的容器组件中,我有: this.props.dispatch(fetchPlace(this.props.match.params.slug)) 我的行动是: import axios from "axios";
/places/:slug
时,会触发一个ajax调用,以从数据库中获取相关的地点数据
虽然这一切工作如预期,我不知道如何显示404如果没有找到的地方。当用户导航到非路由时,我有一个404路由设置,但是如何使用Redux触发404
在我的容器组件中,我有:
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})
})
}
}
还有我的减速机:
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
想法
我可以在我的reducer中使用另一个名为
notFound
的state属性,并将其初始化为false
。然后读取响应数据有效负载并检测作业是否已返回。如果没有,则将notFound
设置为true
。但我如何倾听notFound为真并触发404?我建议从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路由器上下文或历史对象)
另一种方法是检查
组件willreceiveprops(nextrops)
方法中的notFound
值。您使用什么路由器?你有带路由器的redux集成吗?我正在使用react router
v4,并根据你的路由器库写了一个答案
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`)
})