React - How to get parameter value from query string?

后端 未结 30 1692
温柔的废话
温柔的废话 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:39

    You also can use react-location-query package, example:

      const [name, setName] = useLocationField("name", {
        type: "string",
        initial: "Rostyslav"
      });
    
      return (
        <div className="App">
          <h1>Hello {name}</h1>
          <div>
            <label>Change name: </label>
            <input value={name} onChange={e => setName(e.target.value)} />
          </div>
        </div>
      );
    

    name - to get value setName = to set value

    This package has many options, read more in docs on Github

    0 讨论(0)
  • 2020-11-22 10:42

    If your Router is like this

    <Route exact path="/category/:id" component={ProductList}/>
    

    You will get that id like this

    this.props.match.params.id
    
    0 讨论(0)
  • 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<ParamNames extends string[]>(...parameterNames: ParamNames): Record<ParamNames[number], string | null> {
        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<ParamNames[number], string | null>);
        }, [ 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'}
    
    0 讨论(0)
  • 2020-11-22 10:43

    I used an external package called query-string to parse url parameter like so.

    import React, {Component} from 'react'
    import { parse } from 'query-string';
    
    resetPass() {
        const {password} = this.state;
        this.setState({fetching: true, error: undefined});
        const query = parse(location.search);
        return fetch(settings.urls.update_password, {
            method: 'POST',
            headers: {'Content-Type': 'application/json', 'Authorization': query.token},
            mode: 'cors',
            body: JSON.stringify({password})
        })
            .then(response=>response.json())
            .then(json=>{
                if (json.error)
                    throw Error(json.error.message || 'Unknown fetch error');
                this.setState({fetching: false, error: undefined, changePassword: true});
            })
            .catch(error=>this.setState({fetching: false, error: error.message}));
    }
    
    0 讨论(0)
  • 2020-11-22 10:43

    do it all in one line without 3rd party libraries or complicated solutions. Here is how

    let myVariable = new URLSearchParams(history.location.search).get('business');
    

    the only thing you need to change is the word 'business' with your own param name.

    example url.com?business=hello

    the result of myVariable will be hello

    0 讨论(0)
  • 2020-11-22 10:46

    React Router v4

    Using component

    <Route path="/users/:id" component={UserPage}/> 
    
    this.props.match.params.id
    

    The component is automatically rendered with the route props.


    Using render

    <Route path="/users/:id" render={(props) => <UserPage {...props} />}/> 
    
    this.props.match.params.id
    

    Route props are passed to the render function.

    0 讨论(0)
提交回复
热议问题