React Router 只在某些时候工作

React Router only working some times

我目前正在尝试在我正在构建的网站上使用 React Router。我发现使用 React Router 来浏览我的网站,还可以做其他事情,例如读取参数值等。但是,我发现它有点令人困惑。你看,在我的管理员登录页面上,路由器只工作了几次——但我还没有真正弄清楚什么时候和什么时候不工作。我正在使用 this.props.history.push('/admin/dashboard'),我认为这是正确的做法。这是目前我在 index.js 中的设置,我的所有路线都在那里:

import React from 'react';
import ReactDOM from 'react-dom';
import registerServiceWorker from './registerServiceWorker';
import './css-styling/styling.css'
import Frontpage from './Frontpage';
import { BrowserRouter, Route, Router, Switch, Link, NavLink } from 'react-router-dom';
import AdminLogin from './Admin-Login';
import AdminWelcome from './Admin-Welcome';
import Authentication from './components/Authentication';

const websiteRoutes = (
    <Router history={history}>
        <div>
            <Switch>
                <Route path="/" component={Frontpage} exact={true}/>
                <Route path="/admin" component={AdminLogin} exact={true}/>
                <Authentication props={this.props}>
                <Route path="/admin/welcome" component={AdminWelcome} exact={true}/>
                </Authentication>
            </Switch>
        </div>
    </Router>
);

var appRoot = document.getElementById('root');
registerServiceWorker();
ReactDOM.render(websiteRoutes, appRoot);

每个 'component' 的结构如下:

import React from 'react';
import ReactDOM from 'react-dom';
import AdminHeader from './components/Admin-Header';
import AdminPanelLogin from './components/Admin-Panel-Add-News';
import history from './components/History';

class AdminLogin extends React.Component{

    render() {
        return(
            <div>
            <AdminHeader />
            <AdminPanelLogin />
            </div>
        );
    }

}

export default AdminLogin;

这里似乎有什么问题?我尝试了很多不同的解决方案,但没有任何运气。其中之一是创建此 'global history',您可以看到我已将其导入我的 AdminAddNews class。

在我的案例中,使用 React Router 的正确方法是什么?

顺便说一句; history.push 发生在我的 AdminPanelLogin 组件中,代码如下所示:

import React from 'react';
import ReactDOM from 'react-dom';
import { Icon, Input, Button, Message } from 'semantic-ui-react';
import {auth} from './Firebase';
import {NotificationContainer, NotificationManager} from 'react-notifications';
import { withRouter, Redirect } from 'react-router-dom';
import history from './components/History';


class AdminLogin extends React.Component{

constructor(props){
    super(props);

    this.handleLogin = this.handleLogin.bind(this);
    this.clickLogin = this.clickLogin.bind(this);
    this.performLogin = this.performLogin.bind(this);
}


handleLogin(e){
    this.setState({
        [e.target.name]: e.target.value
    });
}


clickLogin(e){
    e.preventDefault();
    auth.signInWithEmailAndPassword(this.state.email, this.state.password).then(() => {
        this.props.history.push('/admin/dashboard');
    }).catch((error)=> {

    })
}

    render() {
        return (
            <HTMLGOESHERE>
        );
    }
}

export default AdminLogin;

实际上,您必须使用 browserHistory,它是 react-router 的一个函数。希望以下代码片段对您有所帮助,

在您的 index.js

中导入 react-router
import {Router, Route, browserHistory} from 'react-router';

ReactDOM.render(
  <Router history={browserHistory} >
    <Route path="/admin/somethingZero" component={somethingZero} />
    <Route path="/admin/somethingOne" component={somethingOne}/>
  </Router> , document.getElementById("root")
)

您可以使用 browserHistory.push 功能在组件之间导航

clickLogin(){
    browserHistory.push('/admin/dashboard')
  }

另外,继续这个tutorial,这样可以更好地理解路由器。

有几点需要更正,

首先: 在你的路线中你已经通过 history 但你没有在任何地方创建自定义历史记录。您现在可以简单地使用 BrowserRouter。

其次:将您的身份验证组件作为包装器写入您的路由,而不是将您的路由用作它的子路由

身份验证:

const PrivateRoute = (props) => {
    const userKey = Object.keys(window.localStorage)
  .filter(it => it.startsWith('firebase:authUser'))[0];
const user = userKey ? JSON.parse(localStorage.getItem(userKey)) : undefined;
   if (user) {
      return <Route {...props} />
   } else {
      return <Redirect to='/admin'/>
   }
}

export default PrivateRoute;

现在你的路线可以

import { BrowserRouter as Router, Route, Router, Switch } from 'react-router-dom';

import Authentication from './Authentication';
const websiteRoutes = (
    <Router>
        <div>
            <Switch>
                <Route path="/" component={Frontpage} exact={true}/>
                <Route path="/admin" component={AdminLogin} exact={true}/>
                <Authentication path="/admin/welcome" component={AdminWelcome} exact={true}/>
            </Switch>
        </div>
    </Router>
);

除此之外检查如何 Programmatically Navigate with react-router