react路由跳转拼接路由和传参数

在react路由传递的过程中,我第一次写的版本是直接把我要的所有参数通过location里的state传递过去,因为我觉得很方便,不用再特地去dispatch请求一次数据,代码像这样:

  update=(record)=>{
        if(record && record.id){
            const than = this;
            confirm({
                title: '修改',
                content: '是否所选信息?',
                okText:'确定',
                cancelText:'取消',
                onOk() {
                const data=record;
                const path = {
                    pathname:'/person/releaseDetial',
                    state:{data,doDispatch:'edit'},
                }
                than.props.dispatch(routerRedux.push(path));     
                },
            });
        }
    }

这样写确实很方便直接在另外一个页面通过this.props.location就可以取到,但是问题是不能刷新,刷新过后就没数据了,只能返回上一页,重新进入当前页面,可是正常操作本页面应该做到,本页面刷新,照常使用,所以我采取了第二种方式,通过拼接路由,将id绑定在路由后面进行跳转.代码如下

router.js里面

'/person/druginfo/:type/:id':{
          component: dynamicWrapper(app, ['personrelease'], () => import('../routes/Person/PersonRelease/ReleaseInfo')),
        },

index.js里面

    update=(record)=>{
        if(record && record.id){
            const than = this;
            confirm({
                title: '修改',
                content: '是否所选信息?',
                okText:'确定',
                cancelText:'取消',
                onOk() {
                const {id}= record;
                than.props.dispatch(routerRedux.push({   
                    pathname: `/person/druginfo/edit/${id}`,
                }))
                },
            });
        }
    }

跳转页面里面

 const pathToRegexp = require('path-to-regexp');
        const match = pathToRegexp('/person/druginfo/:type/:id').exec(this.props.history.location.pathname)
        this.props.dispatch({
            type:'persondrug/getBase',
            payload:{
                idCard:match[2],
            },
        });

这里我们还用到了pathToRegexp,路由的正则匹配,后面.exec跟上你要匹配的路由地址,将返回一个数组.然后我就得到了id号.这就是最近做项目的一些心得

猜你喜欢

转载自blog.csdn.net/weixin_40518538/article/details/80990540