当路由不正确或url中缺少param时,渲染404页面。反应/终极版

时间:2016-11-09 18:33:29

标签: reactjs redux react-router react-redux react-router-redux

以下是我的网址: - http://local.abc.com/pages/red/4

红色,4是参数,如果它不可用或网址不正确,我想重定向到404页面。

为此我在routes.jsx

中添加了以下路线

1] Routes.jsx

import React from 'react'
import { Route, IndexRoute } from 'react-router'
import App from 'layout/app'
import Home from 'pages/home'
import Wagers from 'containers/wagersContainer'
import NotFound from 'pages/notFound'

const ROUTES = (
  <Route path='/' component={App}>
    <IndexRoute component={Home} />
    <Route path="/wagers(/:trackCode)(/:raceNum)" component={Wagers} />
    <Route path="*" component={NotFound}/>
  </Route>
)
export default ROUTES

在这个文件中,我添加了未发现的组件路径。

以下是我的app.jsx

2] App.jsx

import React from 'react'
import Navbar from 'layout/navbar'
import Footer from 'layout/footer'
import LoginPopup from 'common/popups/loginPopup'
import { Router, browserHistory, useRouterHistory } from 'react-router'

export default class App extends React.Component {

componentDidMount() {
    let emptyArr = [null, "undefined", '']
    console.log(this.props.children.params)
    if(this.props.children.params && !_.every(_.values(this.props.children.params))) {
        browserHistory.push('/notFound');
    }
}

render() { 
    return (
        <div>
            <Navbar />
            <div className="pageData">
                {this.props.children}
            </div>
            <Footer />
            <LoginPopup />
        </div>
    )
}

}

这是主要的根组件。

以下是我的index.jsx

3] Index.jsx

require('./main.js');

import React, { PropTypes, Component } from 'react'
import ReactDOM from 'react-dom'
import { Router, browserHistory, useRouterHistory } from 'react-router'
import { Provider } from 'react-redux'
import configureStore from './store/configureStore'


import ROUTES from './routes';
let store = configureStore();

ReactDOM.render(
   <Provider store={store}>
       <Router history={browserHistory} routes={ROUTES} />
   </Provider>,
   document.getElementById('app')

);

当我写错了网址http://local.abc.com/randommmm

然后它会重新发送404页面,但是如果我错过了一些参数,那么它就不会返回404.我该怎么办才能处理未发现的网址。

0 个答案:

没有答案