gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:44:22 26 4
gpt4 key购买 nike

我希望每次 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 };

路由.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;

最佳答案

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

这会导致在您初始化 history 对象时删除监听器。

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

componentDidMount(){

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

编辑:

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

请引用 answer here .

关于javascript - history.listen 在 React Router 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48888333/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com