React-router 在url中带参数的几种方法

1,036 阅读1分钟
import React from 'react';
import { useParams, useLocation, useHistory } from 'react-router-dom';
import qs from 'qs';

function MyUrl () {
    // 跳转url
    const history = useHistory(); // hook: useHistory

    function changeUrl () {
        history.push({
            pathname: '/myurl/2',
            search: 'name=chris',
            state: { fromSource: 1 },
        })
    }

    // 获取match params
    const params = useParams(); // hook: useParams
    const { id } = params;

    // 获取location params
    const location = useLocation(); // hook: useLocation
    const { search, state = {} } = location;
    // 获取location.search中的参数
    const { name } = qs.parse(search.replace(/^\?/, ''));
    // 获取location.state中的参数
    const { fromSource } = state;

    return (
        <div>
            <div>
                myurl id: { id },<br/>
                search name: { name },<br />
                state fromSource: { fromSource },<br />
            </div>
            <div onClick={ changeUrl }>
                change url
            </div>
        </div>
    )
}

export default MyUrl;

// 路由
const route = {
    path: '/myurl/:id',
    component: myUrl,
};
<Route path={route.path} component={route.component} />