如何在我的路由中定义路由。jsx文件捕获__firebase_request_key参数值从一个URL生成的Twitter的单点登录过程后,从他们的服务器重定向?

http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla

我尝试了以下路由配置,但:redirectParam没有捕获提到的参数:

<Router>
  <Route path="/" component={Main}>
    <Route path="signin" component={SignIn}>
      <Route path=":redirectParam" component={TwitterSsoButton} />
    </Route>
  </Route>
</Router>

当前回答

使用let {redirectParam} = useParams();如果你用的是功能组件

它是一个类组件

constructor (props) {  
        super(props);
        console.log(props);
        console.log(props.match.params.redirectParam)
}
async componentDidMount(){ 
        console.log(this.props.match.params.redirectParam)
}

其他回答

在没有第三方库或复杂的解决方案的情况下,在一行中完成这一切。以下是如何

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

你唯一需要改变的是你自己的参数名称的单词“business”。

业务= url.com例子吗?你好

myVariable的结果将是hello

你可以使用这个用Typescript写的简单钩子:

const useQueryParams = (query: string = null) => {      
    const result: Record<string, string> = {};
    new URLSearchParams(query||window.location.search).forEach((value, key) => {
      result[key] = value;
    });
    return result;
}

用法:

// http://localhost:3000/?userId=1889&num=112
const { userId, num } = useQueryParams();
// OR
const params = useQueryParams('userId=1889&num=112');

如果你没有得到这个。道具…根据其他答案,您可能需要使用withthrouter (docs v4):

import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>You are now at {location.pathname}</div>
    )
  }
}

// Create a new component that is "connected" (to borrow redux terminology) to the router.  
const TwitterSsoButton = withRouter(ShowTheLocation)  

// This gets around shouldComponentUpdate
withRouter(connect(...)(MyComponent))

// This does not
connect(...)(withRouter(MyComponent))

不是反应的方式,但我相信这个单行函数可以帮助你:)

const getQueryParams = (query = null) => [...(new URLSearchParams(query||window.location.search||"")).entries()].reduce((a,[k,v])=>(a[k]=v,a),{});

或:

const getQueryParams = (query = null) => (query||window.location.search.replace('?','')).split('&').map(e=>e.split('=').map(decodeURIComponent)).reduce((r,[k,v])=>(r[k]=v,r),{});

或完整版:

const getQueryParams = (query = null) => {
  return (
    (query || window.location.search.replace("?", ""))

      // get array of KeyValue pairs
      .split("&") 

      // Decode values
      .map((pair) => {
        let [key, val] = pair.split("=");

        return [key, decodeURIComponent(val || "")];
      })

      // array to object
      .reduce((result, [key, val]) => {
        result[key] = val;
        return result;
      }, {})
  );
};

例子: URL:…?= = 1 b =建发集团有限公司的测试 代码:

getQueryParams()
//=> {a: "1", b: "c", d: "test"}

getQueryParams('type=user&name=Jack&age=22')
//=> {type: "user", name: "Jack", age: "22" }

你可以使用下面的react钩子:

如果url改变,钩子状态会更新 SSR: typeof window === "undefined",只是检查窗口导致错误(尝试一下) 代理对象隐藏实现,因此返回undefined而不是null

这是获取搜索参数为对象的函数:

const getSearchParams = <T extends object>(): Partial<T> => {
    // server side rendering
    if (typeof window === "undefined") {
        return {}
    }

    const params = new URLSearchParams(window.location.search) 

    return new Proxy(params, {
        get(target, prop, receiver) {
            return target.get(prop as string) || undefined
        },
    }) as T
}

然后像这样把它用作钩子:

const useSearchParams = <T extends object = any>(): Partial<T> => {
    const [searchParams, setSearchParams] = useState(getSearchParams())

    useEffect(() => {
        setSearchParams(getSearchParams())
    }, [typeof window === "undefined" ? "once" : window.location.search])

    return searchParams
}

如果你的url是这样的:

/app?page=2&count=10

你可以这样读:

const { page, count } = useQueryParams();

console.log(page, count)