当redux状态发生变化时,React-Router Switch会导致当前路由重新挂载

时间:2018-03-08 13:33:50

标签: redux react-router react-redux react-router-v4 react-router-dom

我正在使用React-Router v4。但是,每当我的应用程序Redux状态更新时,React-Router的Switch组件都会更新并重新安装当前路由。

我在主index.js文件中定义了我的HashRouter,如下所示:

/* global document */

import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { HashRouter } from 'react-router-dom'
import App from './screens/app/index'
import registerServiceWorker from './registerServiceWorker'

import './styles/main.css'

import store from './store'

ReactDOM.render(
  <Provider store={store}>
    <HashRouter>
      <App />
    </HashRouter>
  </Provider>,
  document.getElementById('root'),
)
registerServiceWorker()

这是我使用Switch组件的组件:

import PropTypes from 'prop-types'
import React from 'react'
import { Route, Switch } from 'react-router-dom'

const propTypes = {
  routes: PropTypes.arrayOf(PropTypes.shape({
    path: PropTypes.string,
    name: PropTypes.string,
    container: PropTypes.object,
    exact: PropTypes.bool,
  })).isRequired,
}

const Router = ({ routes }) => (
  <Switch>
    <div className="container">
      {routes.map(route => (
        <Route
          key={route.path}
          path={route.path}
          exact={route.exact}
          component={() => route.container}
        />
      ))}
    </div>
  </Switch>
)

Router.propTypes = propTypes

export default Router

最后,我在这里设置了我的商店:

import { createStore } from 'redux'

import reducer from './reducers/index'

export default createStore(reducer)

我在想可能的问题可能是:

  • 我的Redux设置存在导致与redux商店冲突的问题
  • 路线未正确定义

1 个答案:

答案 0 :(得分:0)

我怀疑这是每次都重新安装组件的行

component={() => route.container}

尝试

const Router = ({ routes }) => (
  <Switch>
   <div className="container">
     {routes.map(route => {
       const routerComp = () => route.container 
       return (
         <Route
          key={route.path}
          path={route.path}
          exact={route.exact}
          component={routerComp}
        />
       )
     })}
</div>