如何在我的路由中定义路由。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>

当前回答

你可以使用下面的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)

其他回答

如果你没有得到这个。道具…根据其他答案,您可能需要使用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))

React Router v4不再有props.location.query对象(见github讨论)。因此,已接受的答案将不适用于较新的项目。

v4的解决方案是使用外部库查询字符串来解析props.location.search

const qs = require('query-string');
//or
import * as qs from 'query-string';

console.log(location.search);
//=> '?foo=bar'

const parsed = qs.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}

在typescript中,参见下面的示例片段:

const getQueryParams = (s?: string): Map<string, string> => {
  if (!s || typeof s !== 'string' || s.length < 2) {
    return new Map();
  }

  const a: [string, string][] = s
    .substr(1) // remove `?`
    .split('&') // split by `&`
    .map(x => {
      const a = x.split('=');
      return [a[0], a[1]];
    }); // split by `=`

  return new Map(a);
};

在react中使用react-router-dom,你可以做

const {useLocation} from 'react-router-dom';
const s = useLocation().search;
const m = getQueryParams(s);

参见下面的例子

//下面是上面转换和缩小的ts函数 如果(const getQueryParams = t = > {! t | |“字符串”!=typeof t||t.length<2)return new Map;const r=t.substr(1).split("&")。地图(t = > {const r = t.split(" = ");返回[r[0],[1]]});返回新地图(r)}; //一个示例查询字符串 Const s = '?__arg1 = value1&arg2 = value2 ' getQueryParams(s) console.log (m.get (__arg1)) console.log (m.get(最长)) Console.log (m.t get('arg3')) //不存在,返回undefined

你也可以使用react-location-query包,例如:

  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>
  );

名称-获取价值 setName =设置值

这个包有很多选项,在Github上的文档中阅读更多

export class ClassName extends Component{
      constructor(props){
        super(props);
        this.state = {
          id:parseInt(props.match.params.id,10)
        }
    }
     render(){
        return(
          //Code
          {this.state.id}
        );
}