React Router 或 Link 未呈现

React Router or Link Not Rendered

我在 redux 应用程序中使用 react-router-dom。

这是我在 index.js 中的初始设置:

ReactDOM.render(

  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>

  , document.getElementById('root'));

然后在我的 App.js 我有:

render() {
    return (
      <div className="App">
        <Route exact path="/" render={ () => {
          return (
              <div>
                {
                  this.props.categories.map((category)=>{
                    console.log('category', category)
                    return (
                          <Link key={category.name} to="/category"  >{category.name}</Link>
                    )
                  })
                }
              </div>
          )

          }}
        />

        <Route path="/category" render={ () => {
          console.log('category path this.props', this.props)
          return (<p>Category is whatever</p>)
        }}
        />

      </div>
    );
  }

我认为每当我单击任何显示的链接时,浏览器都会自动知道如何呈现新的路由路径/类别,但由于某些原因它不会。

我做错了什么?

来自 React Router 文档,

Generally, React Router and Redux work just fine together. Occasionally though, an app can have a component that doesn’t update when the location changes (child routes or active nav links don’t update). This happens if:

  1. The component is connected to redux via connect()(Comp).
  2. The component is not a “route component”, meaning it is not rendered like so: <Route component={SomeConnectedThing}/>

The problem is that Redux implements shouldComponentUpdate and there’s no indication that anything has changed if it isn’t receiving props from the router. This is straightforward to fix. Find where you connect your component and wrap it in withRouter.

所以可能是使用 render 道具的问题。所以:

  1. render 替换为 component,或者
  2. 尝试他们的解决方案,withRouter(即使在那里你也必须将它们制作成组件)

https://reacttraining.com/react-router/core/guides/redux-integration/blocked-updates

Dane 的上述 post 提供了解决方案。 但本着更清晰地呈现解决方案的精神,我将复制并粘贴使 React Router 与 Redux 和其他中间件一起工作的相关代码。

import { withRouter } from 'react-router-dom'



export default withRouter(connect(
  mapStateToProps,
)(App))

Link 和路由器都是必填项。

Not Work!

import { BrowserRouter as Link } from "react-router-dom";

Work in my case.

import { BrowserRouter as Router, Link } from "react-router-dom";

就我而言,这是正常工作的。如果您将同时导入路由器和 link。

import { BrowserRouter as Router, Link } from "react-router-dom";