【问题标题】:React-router-dom and Redirect not being added to history?React-router-dom 和 Redirect 未添加到历史记录中?
【发布时间】:2018-07-21 17:19:24
【问题描述】:

大纲:

我目前正在努力学习react/redux/router。作为一个实践项目,我正在开发一个基本的联系人/客户管理应用程序。在使用react-router-doms Redirect 组件时。我无法让后退/前进导航按预期工作。

详情:

我有一个表,其中包含位于 /contacts/ 的条目列表,当您单击其中一个表行时,我想使用 <tr>s onClick 属性设置的值来 Redirect

点击<tr key={d._id} onClick={()=>this.setState({ id: d._id })}> 会将state.id 更改为clientIDs 的唯一值。这会导致 Redirect 在表格渲染方法中为真,从而触发 Redirect

render() { // render method of '/contacts/' {Contacts} component
    return(
        ... // table head
        { this.state.id && <Redirect to={"/contacts/card/"+this.state.id}/> }
        ...// table content
    )
}

这是位于父App.js的路由器

render() {
    return (
        <BrowserRouter basename="/" >
            <div>
                <NavBar/>
                <main>
                    <Switch>
                        <Route exact path="/" component={Login}/>
                        <Route 
                            exact path="/contacts" component={Contacts}/>
                        <Route
                            exact
                            path="/contacts/card/:clientID" component={ContactCard}/>
                    </Switch>
                </main>
            </div>
        </BrowserRouter>
    );
}

问题:

重定向后,如果您从/contacts/card/:clientID 单击返回按钮,浏览器不会返回到/contacts/。相反,它会循环访问我查看过的任何以前的 :clientID URL。

我尝试将&lt;tr&gt; 包装在路由器&lt;Link to={}&gt; 标记中,但它破坏了样式。

警告: (this.state.id)

我知道我应该使用Redux 来为我的重定向功能保存this.state.id 的值。我还没有完全掌握如何使用单个 redux reducer 管理多个值。一旦我这样做了,我会用适当的方法更新问题。

【问题讨论】:

    标签: reactjs redux react-router-dom


    【解决方案1】:

    找到了答案,我需要像这样将push 添加到我的&lt;Redirect/&gt; 组件中。

    <Redirect push to={`/contacts/card/${this.state.id}`}/>
    

    来自文档:

    &lt;Redirect/&gt;

    推:布尔

    如果为 true,重定向会将新条目推送到历史记录中,而不是替换当前条目。

    【讨论】:

    • 谢谢你 - 让我头疼了好几个小时。
    猜你喜欢
    • 2022-07-18
    • 2016-08-21
    • 1970-01-01
    • 2021-01-04
    • 2015-04-16
    • 2017-08-17
    • 2012-11-25
    • 2020-12-07
    • 2020-10-16
    相关资源
    最近更新 更多