React路由器不会在历史记录更改时呈现新组件

时间:2017-09-19 11:31:03

标签: reactjs redux react-router history react-router-dom

所以基本上,当我尝试从其中一条路线改变路线时,我正在调用this.props.history.push('/ newPath')。浏览器URL更改,但新路径不匹配(我假设),因为相同组件的渲染功能被调用,没有任何变化..

index.tsx with router:

import * as React from 'react';
import * as ReactDOM from "react-dom";
import { Router, Route } from 'react-router-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import history from '../services/history.js';

import rootReducer from '../reducers';

import Browse from './browse';
import ShopItem from './shop-item';

import * as Styles from './index.scss';

const BrowserContainer = () => {
  const initialState: any = {
    items: window.preloadedData.items || []
  };
  const middlewares = [thunk];
  const store = createStore(rootReducer, initialState, 
applyMiddleware(...middlewares));

  return (
    <Provider store={ store }>
      <Router history={ history }>
        <div className={ Styles['container'] }>
          <Route exact path="/item/:id" component={ ShopItem } />
          <Route exact path="/home" component={ Browse } />
        </div>
      </Router>
    </Provider>
  );
};

ReactDOM.render(
  <BrowserContainer />,
  document.getElementById("root")
);

我尝试导航的组件使用connect函数连接到redux存储。我已经尝试将其包装到withRouter()HOC并删除连接,但没有成功。功能我打电话来改变路线:

getItemAndNavigate(id: string) {
  this.props.history.push(`/item/${id}`);
}

版本:     “历史”:“^ 4.7.2”,     “react-router-dom”:“^ 4.2.2”

1 个答案:

答案 0 :(得分:0)

您需要使用this.context.router.history.push。在Chrome中检查调试器。他们升级到版本4.它完全重写了以前的版本。如果您需要更多帮助,请告诉我。设置断点以查看返回的内容。此外,<Router>现在是<BrowserRouter>。你不再需要历史了。

编辑:我犯了一个错误并使用this.props.router.history,它应该使用context并使用BrowserContainer.contextTypes = {router:PropTypes.object};