【问题标题】:How can I change the URL without rendering another component or redirecting to a different route in React?如何在不渲染另一个组件或重定向到 React 中的不同路由的情况下更改 URL?
【发布时间】:2019-04-17 19:05:35
【问题描述】:

在我想到的示例中,我在/projects 有一个索引页。如果我单击页面上的某个项目,则会弹出一个包含更多详细信息的模式。现在我希望我的用户能够在打开模式的页面上添加书签,在一个像 /projects/1 这样的合理 URL 上。

如果我使用this.props.history.push("projects/1") 更改 URL,除非我先定义路由,否则浏览器中不会显示任何内容。但实际上我根本不想要一条单独的路线,只是一种改变 URL 外观的方法,除了显示模式之外不呈现其他一些组件(所以这个问题与例如 Changing the URL in react-router v4 without using Redirect or Link 不同)。

有谁知道该怎么做,或者是否有可能?

FWIW,这是我在 App.js 中的路由:

    <Router>
        <div>
          <NavBar/>
          <Switch>
            <Route exact path='/' render={(props) => <Home {...props} buttonVisible={true} />}/>
            <Route exact path='/projects' render={(props) => <ProjectsContainer {...props} projects={this.props.projectList} />} />
            <Route path='/projects/:projectId/result' component={ResultsContainer} />
            <Route exact path='/projects/new' render={(props) => (<div><Home {...props} buttonVisible={false}/></div>)}/>
          </Switch>
        </div>
    </Router>

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    你可以使用嵌套路由

    将您的项目路线转换为

    <Route path='/projects' render={(props) => <ProjectsContainer {...props} projects={this.props.projectList} />} />
    

    然后在项目容器中添加另一个 Route 组件,例如

    <Route path={`${match.path}/:id`} render={(props) => /* here you get the id via props.match.params.id */ } />
    

    用创建模态的代码替换我的评论

    这允许您为特定项目的链接添加书签并仅通过链接来控制模式

    【讨论】:

    • 这很聪明!我会尝试并报告。
    猜你喜欢
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    相关资源
    最近更新 更多