我有一个简单的reactjs应用程序,它与rest api对话,并希望它在api返回404时提供catch all路由。
因为我使用的是react-router-v4,所以我尝试了this.props.history.push("/404");,它确实提供了正确的组件,但也更改了der浏览器中的URL。URL的这种更改是我不想要的
我有以下代码
App.js
class App extends Component {
render() {
return (
<Switch>
<Route exact path='/' component={Calendar}/>
<Route path='/day/:number' component={Day}/>
<Route component={Error404}/>
</Switch>
);
}
}在Day.js中,我会这样做
componentDidMount() {
const dayNumber = parseInt(this.props.match.params.number);
jQuery.ajax('http://localhost:9018/api/day/' + dayNumber)
.done((result) => {
this.setState({
day: result
});
})
.fail(() => {
this.props.history.push("/404");
});
}因此,当我浏览到像/no-match这样的网址时,应用程序会呈现Error404组件,而网址仍在/no-match上<-正确
当我在网上冲浪时,应用程序会呈现/day/1组件,后端返回200。URL停留在/day/1 <-正确
当我在网上冲浪时,应用程序会呈现/day/35组件,后端返回404。重定向将Error404组件和URL更改渲染到/404 <-这不是我想要的。
因此,我明白推动历史可能是错误的。但是,我如何实现一个通用的解决方案,为整个应用程序中每个失败的应用程序接口调用呈现Error404呢?
发布于 2019-02-01 05:35:48
您可以根据结果设置状态'status‘:
componentDidMount() {
const dayNumber = parseInt(this.props.match.params.number);
jQuery.ajax('http://localhost:9018/api/day/' + dayNumber)
.done((result) => {
this.setState({
day: result, status: 'SUCCESS',
});
})
.fail(() => {
this.setState({ status: 'ERROR' })
});
}然后,在渲染中,您可以显示您喜欢的组件:
render() {
return (
<div>
{this.state.status === 'SUCCESS' ? 'show day content' : 'show ErrorComponent'}
</div>
);
}根据你的整个应用上下文,来自react-router的createMemoryHistory可能也值得一看,但据我所知,它只用于测试/本机应用。
https://stackoverflow.com/questions/54469233
复制相似问题