history的相关API
作者:互联网
push和replace
push是压入栈,留下访问痕迹,replace是代替,不留下访问痕迹
如果全部变为replace,那么就不会有后退功能了
goback:history中实现后退的函数
goForward:history中实现前进的函数
go:history中实现前进后退几步的函数,go(2)表示前进2步,go(-2)表示后退2步
代码如下
export default class Message extends Component { state = { messageArr: [ { id: '1', title: '消息1' }, { id: '2', title: '消息2' }, { id: '3', title: '消息3' } ] } handleReplace = (id, title) => { this.props.history.replace(`/home/message/detail/${id}/${title}`) } handlePush = (id, title) => { this.props.history.push(`/home/message/detail/${id}/${title}`) } handeleForward = () => { this.props.history.goForward() } handleBack = () => { this.props.history.goBack() } handleGo = () => { this.props.history.go(2) } render() { return ( <div> <ul> { this.state.messageArr.map((msgObj) => { return ( <li key={msgObj.id}> {/* 向路由组件传递params传递参数 */} <Link to={"/home/message/detail/" + msgObj.id + "/" + msgObj.title}>{msgObj.title}</Link> <button onClick={() => this.handlePush(msgObj.id, msgObj.title)}>push查看</button> <button onClick={() => this.handleReplace(msgObj.id, msgObj.title)}> replace查看</button> {/* 向路由组件传递search传递参数 */} {/* <Link to={`/home/message/detail/?id=${msgObj.id}&title=${msgObj.title}`} >{msgObj.title}</Link> */} {/* 向路由组件传递state传递参数 */} {/* <Link to={{ pathname: "/home/message/detail", state: { id: msgObj.id, title: msgObj.title } }} >{msgObj.title}</Link> */} </li> ) }) } <hr /> {/* 声明接收params参数 */} <Route path="/home/message/detail/:id/:title" component={Detail} /> <button onClick={this.handeleForward}>前进</button> <button onClick={this.handleBack}>后退</button> <button onClick={this.handleGo}>go</button> {/* 声明接收search参数 ,无需声明接收,正常注册理由即可*/} {/* <Route path="/home/message/detail" component={Detail} /> */} {/* 声明接收state参数 ,无需声明接收,正常注册理由即可*/} {/* <Route path="/home/message/detail" component={Detail} /> */} </ul> </div> ) } }
备注:使用search和state传参也都一样可以
标签:msgObj,title,replace,API,go,相关,id,history 来源: https://www.cnblogs.com/shuchenhao/p/16219299.html