如何设置React V4 BrowserHistory工作?

时间:2019-01-04 18:31:20

标签: reactjs firebase redirect browser-history

我的 React 版本是' ^ 16.6.1 ',而 Router 版本是' ^ 4.3.1 '。

V4 之前,我可以使用browserhistory以编程方式浏览页面。

但是现在我做不到。我是使用import createHistory from 'history/createBrowserHistory'完成的。它会根据需要更改网址。但这并没有改变页面。它留在上一页。

请给我一个解决方案。

这是我的代码。

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter as Router } from "react-router-dom";

ReactDOM.render(
    <Router>
        <App />
    </Router>,
    document.getElementById("root")
);
serviceWorker.unregister();

// App.js

import React, { Component } from 'react';
import './App.css';
import createHistory from 'history/createBrowserHistory'
import { Route, Redirect } from 'react-router-dom';
import firebase from './firebase';
import Routes from "./Routes";
import NavigationBar from './components/NavigationBar/NavigationBar';

class App extends Component {

  constructor() {
    super();
    this.state = { isLogged: false };
    let ctx = this;
    const history = createHistory();
    firebase.auth().onAuthStateChanged(function (user) {
        if (user) {
            // User is signed in.
            console.log("logged in");
            history.replace('/home');
            ctx.setState({ isLogged : true});
        } else {
            // No user is signed in.
            console.log("not logged in");
            ctx.setState({ isLogged : false});
        }
    });
  }

  render() {
    return (
      <div className="App">
        <NavigationBar />
        <Routes />
      </div>
    )
  }
}

export default App;

// Routes.js

import React from 'react';
import { Route, Switch } from "react-router-dom";
import Login from './components/Admin/Login';
import Home from './components/Home/Home';
import Orchids from './components/Orchids/Orchids';
import Anthurium from './components/Anthurium/Anthurium';
import ContactUs from './components/ContactUs/ContactUs';
import AddOrchid from './components/Admin/AddOrchid';

export default (props) =>
  <Switch>
    {/* <Route path="/" exact component={LandingPage} /> */}
    <Route path="/" exact component={Home} />
    <Route path="/home" exact component={Home} />
    <Route path="/orchids" component={Orchids} />
    <Route path="/anthurium" component={Anthurium} />
    <Route path="/contact-us" component={ContactUs} />
    <Route path="/login" component={Login} />
    <Route path="/add-orchid" component={AddOrchid} />
  </Switch>;

1 个答案:

答案 0 :(得分:0)

由于您已经在react-router-dom模块中使用了BrowserRouter,因此可以在BrowserRouter组件的子级中简单地使用this.props.history.push("/yourPath")