【问题标题】:history.listen not working correctly inside React Routerhistory.listen 在 React Router 中无法正常工作
【发布时间】:2018-07-30 23:55:06
【问题描述】:

我希望能够在每次 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;

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

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

    它导致,在您初始化 history 对象时,监听器被移除。

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

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

    编辑:

    看起来,你需要集成react-router-redux

    请参考answer here

    【讨论】:

    • 感谢您的帮助,但很遗憾,我仍然没有看到控制台日志
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 2022-12-04
    • 2021-08-02
    • 2018-11-27
    • 1970-01-01
    • 2018-11-30
    相关资源
    最近更新 更多