React - How to get parameter value from query string?

后端 未结 30 1722
温柔的废话
温柔的废话 2020-11-22 10:22

How can I define a route in my routes.jsx file to capture the __firebase_request_key parameter value from a URL generated by Twitter\'s single sign on process a

30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 10:42

    You could create simple hook for extracting search params from current location:

    import React from 'react';
    import { useLocation } from 'react-router-dom';
    
    export function useSearchParams(...parameterNames: ParamNames): Record {
        const { search } = useLocation();
        return React.useMemo(() => { // recalculate only when 'search' or arguments changed
            const searchParams = new URLSearchParams(search);
            return parameterNames.reduce((accumulator, parameterName: ParamNames[number]) => {
                accumulator[ parameterName ] = searchParams.get(parameterName);
                return accumulator;
            }, {} as Record);
        }, [ search, parameterNames.join(',') ]); // join for sake of reducing array of strings to simple, comparable string
    }
    

    then you could use it inside your functional component like this:

    // current url: http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla
    const { __firebase_request_key } = useSearchParams('__firebase_request_key');
    
    // current url: http://localhost:3000/home?b=value
    const searchParams = useSearchParameters('a', 'b'); // {a: null, b: 'value'}
    

提交回复
热议问题