【问题标题】:React Router not re-rendering components on click, but works on refreshReact Router 不会在单击时重新渲染组件,但可以在刷新时使用
【发布时间】:2018-07-29 16:47:54
【问题描述】:

我在Dashboard 组件上呈现了一个左侧,旁边是当前选定页面的占位符。链接按预期更改 URL,例如dashnoard/permissions,但未呈现权限组件。但是,如果手动刷新页面,它将起作用。这是我现在正在尝试的。

class App extends Component {

  render() {
    return (
      <Router>
        <MultiThemeProvider>
          <div className="App" id="siteWrap">
            <AppBar title="DiversityEDU" />
            <switch>
              <Route exact={true} path="/"  component={Home}/>
              <Route exact={true} path="/login" handler={Login} component={Login}/>
              <Route path="/dashboard" component={Dashboard}/>
            </switch>
          </div>
        </MultiThemeProvider>
      </Router>
    );
  }
}

class Dashboard extends Component {
  constructor(props){
    super(props);
  }
  render() {
    return (
      <Router>
        <div id="dashboardWrap" style={style.dashboardWrap}>
          <Sidebar links={links}/>
          <div style={style.dashboardContent}>
            <p>Dashboard has rendered</p>
            <switch>
              <Route exact={true} path="/dashboard/roles" component={Roles}/>
              <Route exact={true} path="/dashboard/permissions" component={Permissions}/>
            </switch>
          </div>
        </div>
      </Router>
    );
  }
}

我也在这个项目中使用 Redux,但还没有直接在上面的组件中使用。

const AppContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

【问题讨论】:

  • 你在这里使用componentrendercomponent={Dashboard} render={() =&gt; (&lt;Dashboard/&gt;),使用任何一个试试。
  • 我将代码更新为仅使用组件。同样的行为。
  • 您在两个文件中都使用了&lt;Router&gt;,在App 文件中只使用一次并从所有其他文件中删除。
  • 您只需要在顶层而不是嵌套路由中的路由器,也请检查此答案stackoverflow.com/questions/44356360/…
  • 谢谢@MayankShukla。我也在 周围使用 ,并且删除那些没有其他代码更改的问题解决了这个问题。

标签: reactjs react-router


【解决方案1】:

在组件中使用上下文路由器来更改路由。

constructor(props,context){
super(props,context)
}
this.context.router.history.push({pathname:sth/sth})

Dashboard.contextTypes = {
router: PropTypes.object.isRequired
}

【讨论】:

  • 您的回答对我没有帮助,因为我不知道这段代码的去向。请使用更多上下文更新您的答案,如果有效,我可以将其标记为正确。谢谢:-)
  • 你不应该对框架的内部做任何假设,例如。 react-router 如何在上下文中传递信息或它如何操纵历史。除非您自己编写框架,否则通常不鼓励您自己访问 react 上下文。对于这个用例,react-router 提供了一个 &lt;Redirect&gt; 组件,可以简单地使用重定向到的路径进行渲染。
  • 唯一的问题是我有不止一个&lt;Router&gt;,在我的&lt;Link&gt;s 周围是多余的。删除它并解决问题。
【解决方案2】:

为每个组件路由分配开关,然后从确切的路由中删除={true},然后将exact 添加到仪表板路由

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-13
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    相关资源
    最近更新 更多