跳转页面 -- withRouter

在这里插入图片描述
创建页面和修改页面为同一个js, 方法不同,修改为put方法, 创建为post方法, 但是当创建成功时, 页面可以跳转成功, 但当修改时无法跳转, url为同一个url 为甚???

使用 withRouter
在这里插入图片描述
在这里插入图片描述

withRouter组件

默认情况下必须经过路由匹配渲染的组件才存在this.props,才拥有路由参数,执行this.props.history.push(’/detail’)跳转到对应路由的页面,然而不是所有组件都直接与路由相连(通过路由跳转到此组件)的,当这些组件需要路由参数时,使用withRouter就可以给此组件传入路由参数,将react-router的history、location、match三个对象传入props对象上,此时就可以使用this.props。

eg:
比如app.js这个组件,一般是首页,不是通过路由跳转过来的,而是直接从浏览器中输入地址打开的,如果不使用withRouter此组件的this.props为空,没法执行props中的history、location、match等方法。
使用时可以通过下面两种方式:

1.在要注入属性的组件上使用’@withRouter’

2.类似‘withRouter(App)’

import React,{Component} from 'react'
import {Switch,Route,NavLink,Redirect,withRouter} from 'react-router-dom' //引入withRouter
import One from './One'
import NotFound from './NotFound'
/*或者直接在组件上使用‘@withRouter’*/
class App extends Component{
    //此时才能获取this.props,包含(history, match, location)三个对象
    console.log(this.props);  //输出{match: {…}, location: {…}, history: {…}, 等}
    render(){return (<div className='app'>
            <NavLink to='/one/users'>用户列表</NavLink>
            <Switch>
                <Route path='/one/:type?' component={One} />
                <Redirect from='/' to='/one' exact />
                <Route component={NotFound} />
            </Switch>
        </div>)
    }
}
export default withRouter(App);  //这里要执行一下WithRouter

参考: https://juejin.im/post/5bae31b0e51d450e827b568e

发布了47 篇原创文章 · 获赞 42 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/zm_miner/article/details/89404137