我有一条带params的路线,我想渲染/重定向到404路线如果某个操作返回没有数据来自 外部API 。最明智的做法是什么?
这是路由器:
export default (
<Route path="/" component={App}>
<Route path=":venueName" component={Venue} />
<Route path="*" component={NotFound} />
</Route>
);
Venue组件连接到Redux并触发一个动作:
// ...
componentWillMount() {
this.props.actions.fetchVenue(this.props.id);
// want to redirect to 404 if this returns success === false
}
// ...
动作如下:
export const fetchVenue = (id) => ({
type: 'FETCH_VENUE',
payload: axios.get('http://someAddress/api/venues/id'),
});
我在这里遇到的问题是如何通过服务器端呈现和任意数量的路由来解决这个问题。我在express中使用来自react-router的“匹配”来呈现标记。如果您希望我发布更多代码,请告诉我。
答案 0 :(得分:6)
这个组件不适合这种逻辑,恕我直言。我在我的操作中执行此操作,并使用react-router
的`browserHistory。如下所示:
export function fetchBrand(id) {
return function(dispatch) {
fetchData(`brands/${id}`, {
headers: { 'X-Token-Auth': localStorage.getItem('token')}
}).then(response => {
dispatch({
type: FETCH_BRAND_SUCCESS,
payload: response
});
}).catch(err => {
if (err.response.status == 404) {
browserHistory.push("/my404page");
}
});
}
}
例如,我有某种route
到my404page
。