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

其他回答

你可以使用这个用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');
componentDidMount(){
    //http://localhost:3000/service/anas
    //<Route path="/service/:serviceName" component={Service} />
    const {params} =this.props.match;
    this.setState({ 
        title: params.serviceName ,
        content: data.Content
    })
}

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

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-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上的文档中阅读更多

从v4开始,React路由器不再直接在其location对象中提供查询参数。原因是

There are a number of popular packages that do query string parsing/stringifying slightly differently, and each of these differences might be the "correct" way for some users and "incorrect" for others. If React Router picked the "right" one, it would only be right for some people. Then, it would need to add a way for other users to substitute in their preferred query parsing package. There is no internal use of the search string by React Router that requires it to parse the key-value pairs, so it doesn't have a need to pick which one of these should be "right".

包含了这个之后,只解析location会更有意义。在需要查询对象的视图组件中搜索。

你可以通过覆盖react-router中的withRouter来实现这一点

customWithRouter.js

import { compose, withPropsOnChange } from 'recompose';
import { withRouter } from 'react-router';
import queryString from 'query-string';

const propsWithQuery = withPropsOnChange(
    ['location', 'match'],
    ({ location, match }) => {
        return {
            location: {
                ...location,
                query: queryString.parse(location.search)
            },
            match
        };
    }
);

export default compose(withRouter, propsWithQuery)