首页 > 解决方案 > React Router props `location` / `match` 未使用 `ConnectedRouter` 更新

问题描述

我已经按照文档设置了我的应用程序:

步骤1

...
import { createBrowserHistory } from 'history'
import { applyMiddleware, compose, createStore } from 'redux'
import { connectRouter, routerMiddleware } from 'connected-react-router'
...
const history = createBrowserHistory()

const store = createStore(
  connectRouter(history)(rootReducer), // new root reducer with router state
  initialState,
  compose(
    applyMiddleware(
      routerMiddleware(history), // for dispatching history actions
      // ... other middlewares ...
    ),
  ),
)

第2步

...
import { Provider } from 'react-redux'
import { Route, Switch } from 'react-router' // react-router v4
import { ConnectedRouter } from 'connected-react-router'
...
ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}> { /* place ConnectedRouter under Provider */ }
      <div> { /* your usual react-router v4 routing */ }
        <Switch>
          <Route exact path="/" render={() => (<div>Match</div>)} />
          <Route render={() => (<div>Miss</div>)} />
        </Switch>
      </div>
    </ConnectedRouter>
  </Provider>,
  document.getElementById('react-root')
)

我点击一个Link甚至dispatch(push('/new-url/withparam'))

但是,道具match location保留了以前的值或第一页的任何内容。

怎么了?

标签: react-routerreact-reduxreact-router-domconnected-react-router

解决方案


这个已经咬过我很多次了。

您的SwitchRoute不得位于连接的组件内!

如果组件已连接,则 , 等的道具match似乎location不会更新并传播到您的路线。

这意味着不要在and之间连接您的顶层ApporRoot或任何其他嵌套容器ConnectedRouterRoute

--

更新:

您可能只需要用

<Route render={ (routerProps) => <YourConnectedComponent { ...routerProps } />

推荐阅读