大纲:
我目前正在尝试学习react/redux/router。作为一个实践项目,我正在开发一个基本的联系人/客户管理应用程序。使用react-router- doms Redirect组件时。我无法使后退/前进导航正常工作。
react/redux/router
react-router- dom
Redirect
细节:
我有一个表,其中包含条目列表,/contacts/当您单击表行之一时,我想Redirect使用由<tr>s onClick属性设置的值。
/contacts/
<tr>
单击<tr key={d._id} onClick={()=>this.setState({ id: d._id })}>更改state.id为clientID的唯一值。这导致Redirect表render方法为true,从而触发Redirect。
<tr key={d._id} onClick={()=>this.setState({ id: d._id })}>
state.id
clientID
render() { // render method of '/contacts/' {Contacts} component return( ... // table head { this.state.id && <Redirect to={"/contacts/card/"+this.state.id}/> } ...// table content ) }
这是位于父级中的路由器 App.js
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。
/contacts/card/:clientID
:clientID
我尝试将包裹<tr>在路由器<Link to={}>标签中,但是它破坏了样式。
<Link to={}>
警告: (this.state.id)
this.state.id
我知道我应该Redux用来保存this.state.id重定向功能的值。我还没有完全掌握如何使用单个redux reducer来管理多个值。完成后,我将使用适当的方法更新问题。
Redux
找到了答案,我需要像这样添加push到我的<Redirect/>组件中。
push
<Redirect/>
<Redirect push to={`/contacts/card/${this.state.id}`}/>
从文档:
<Redirect/> 推:布尔 设置为true时,重定向会将新条目推入历史记录,而不是替换当前条目。
推:布尔
设置为true时,重定向会将新条目推入历史记录,而不是替换当前条目。