【问题标题】:Adding the sub Route in the react js React router v4在 react js React router v4 中添加子路由
【发布时间】:2019-02-04 06:02:24
【问题描述】:

我是 react 路由器的新手。我所拥有的是,

Main.js

render() {
    return (
      <Router history={history}>
        <div>
          {this.props.isFetching && <Loading />}
          <Switch>
            <PrivateRoute exact path="/" component={LandingPage} />
            <PrivateRoute exact path="/create-job" component={NewJob} />
            <Route exact path="/login" component={Login} />
          </Switch>
        </div>
      </Router>
    )
  }
}

现在,在这里,我的路线是 create-job 。现在,这里有一个容器NewJob.js

 render() {
    return (
      <Fragment>
        <SubHeader isAuthenticated={localStorage.getItem("access_token") ? true : false} />
        <JobNotFound />
      </Fragment>
    )
  }

现在,在JObNotFound.js 中有一个类似的按钮,

<div className="col-sm-4">
                <button className="btn btn-lg btn-primary btn-block button-container">Create New Job</button>
            </div>

现在,我要做的是,onclick of this button,我想将路由更改为create-job/New,并想在那里渲染一个新组件。

所以,我在这个地方完全糊涂了。谁能帮我解决这个问题?

谢谢。

【问题讨论】:

    标签: javascript reactjs redux react-redux react-router-v4


    【解决方案1】:

    您可以使用按钮组件Programmatically navigate onClick的react-router中的Link组件

      import { Link } from 'react-router-dom';
    
      ...
    
    
      <div className="col-sm-4">
            <Link to="create-job"><button type='button' className="btn btn-lg btn-primary btn-block button-container">Create New Job</button></Link>
      </div>
    

    【讨论】:

    • 所以,我只需要将它与 to=create-job/new 一起使用,然后在主组件中使用
    • 是的,还要确保 JobNotFound 页面使用 &lt;Route component={JobNotFound} /&gt; 呈现,以便它接收路由器道具并且链接正常工作,否则您可以像 export default withRouter(JobNotFound) 那样导出 JobNotFound ,其中 withRouter 是从 react-router 导入的dom
    • 好的,我将在 JobNotFound 页面中添加 withRouter
    • 因为我很困惑应该在哪里使用那个
    • 你在哪里渲染&lt;JobNotFound /&gt;
    【解决方案2】:

    在JobNotFound.js中,导入withRouter,然后包装组件

    import {withRouter} from 'react-router-dom'
    ...
    //at the bottom
    export default withRouter(JobNotFound)
    

    然后在绑定 onClick 按钮如下:

    <div className="col-sm-4">
        <button onClick={()=>{this.props.history.push(`${process.env.PUBLIC_URL}/create-job/New`)}} className="btn btn-lg btn-primary btn-block button-container">Create New Job</button>
     </div>
    

    【讨论】:

      猜你喜欢
      • 2017-09-08
      • 2018-01-11
      • 1970-01-01
      • 2017-11-11
      • 2018-01-18
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      相关资源
      最近更新 更多