history.listen在React Router中无法正常工作

时间:2018-02-20 15:10:42

标签: javascript reactjs react-router

我希望每次React都能识别出url已更改时调用函数,但是我遇到了history.listen没有触发的问题(从不打印console.log)。我看过帖子说这是因为我正在使用BrowserRouter,但每当我尝试从react-router导入任何东西时,我都会收到错误,说“无法在react-router中找到x”。我目前有react-router和react-router-dom版本4.1.2

App.js

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import { BrowserRouter, Route, Redirect, Link } from 'react-router-dom';

import './App.css';
import reducers from './common/reducers'
import Routes from './common/Routes';
import RoutesWrapper from './components/RoutesWrapper';
import Login from './Login';

class App extends Component {

    render() {
        const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));

        return (
            <Provider store={store}>
                <BrowserRouter>
                    <Login>
                        <div className="App">
                            <div className="widgetCont">
                                <Routes wrapper={RoutesWrapper}/>
                            </div>
                        </div>
                    </Login>
                </BrowserRouter>
            </Provider>
        );
    }
}

export default App;
export { Route, Redirect, Link };

Routes.js

import React, { Component } from 'react';
import createHistory from 'history/createBrowserHistory';

import { Route } from '../App.js';
import PredictionsCompletedContainer from './containers/PredictionsCompletedContainer';
import GameContainer from './containers/GameContainer';

class Routes extends Component {


    render() {
        const Wrapper = this.props.wrapper;

        const history = createHistory();
        history.listen((location, action) => {
            console.log("inside history listen");
        });

        return (
            <Wrapper>
                <Route exact path="/" component={GameContainer}/>
                <Route path="/predictions-completed" component={PredictionsCompletedContainer}/>
            </Wrapper>
        );
    }
}

export default Routes;

1 个答案:

答案 0 :(得分:1)

每次重新渲染组件时,都会调用渲染。

导致,在初始化history对象时,侦听器被删除。

它更好,把它放在组件生命周期componentDidMount中,它在生命中只调用一次。

componentDidMount(){

    const history = createHistory();
        history.listen((location, action) => {
            console.log("inside history listen");
        });
}

编辑:

看起来,您需要整合 react-router-redux

请参阅 answer here