首页 > 解决方案 > 反应路由器 this.props.history.location 未定义

问题描述

我对反应和反应路由器很陌生,我遇到了一些问题。我想实现一个重定向功能可以这么说,但它给了我this.props.history.location is undefined错误

index.js - 应用在这里被路由器包裹

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './app/App.js';
import Test from "./pages/users/users";
import {BrowserRouter, Redirect, Route, Router, Switch} from "react-router-dom";
import createHistory from "history/createBrowserHistory"
import registerServiceWorker from './registerServiceWorker';
import history from './utilities/history'


const app = (
        <Router history={history}>
            <Route path="/:currentPage?" component={App} />
        </Router>
);

ReactDOM.render(app, document.getElementById('root'));
registerServiceWorker();

App.js -- 主应用

export class App extends Component {
    state = {};


 handleChange = () => {
        console.log(this.props);
        const {user, match, history} = this.props;
        const currentPath = match.params.currentPage;
        const userIsSigningIn = currentPath === "/" + SIGN_IN_PAGE.path;
        console.log(this.state.user);
        if (this.state.user && currentPath === "/sign-in") {
            // history was passed from client/src/index.js
            this.props.history.replace('/remittances');
        } else if (currentPath !== "/sign-in" && !this.state.user) {
            this.props.history.replace('/sign-in');
        }
        return;

  render() {
    //this is our initial page
    const {user, match, history} = this.props;
    const currentPath = match.params.currentPage;


     return (
            <div className="page-container">
                <Switch>
                    {/*note: important to pass functions as lambdas */}
                    <Route path="/sign-in" render={() => <SignInPage attemptSignIn={this.attemptSignIn}/>}/>
                    <Route path="/inventory" render={() => <InventoryPage/>}/>
                    <Route path="/remittances" render={() => <RemittancePage/>}/>
                    <Route path="/inventory" render={() => <RemittancePage/>}/>
                    <Route path="/users" render={() => <UsersPage/>}/>
                </Switch>

                {/*render navbar if there is a user and path is not sign-in*/}
                {!this.state.user && currentPath !== "/sign-in" &&
                <NavBar/>
                }
            </div>
        );
    }
}
export default withRouter(App)

任何形式的帮助都会谢谢你!

标签: javascriptreactjs

解决方案


推荐阅读