在 React Native 中使用 Fetch 获取查询字符串

GET with query string with Fetch in React Native

我提出这样的请求:

fetch("https://api.parse.com/1/users", {
  method: "GET",
  headers: headers,   
  body: body
})

如何传递查询字符串参数?我只是将它们添加到 URL 吗?我在 docs.

中找不到示例

您的第一个想法是正确的:只需将它们添加到 URL。

请记住,您可以使用模板字符串(反引号)来简化将变量放入查询中的过程。

const data = {foo:1, bar:2};

fetch(`https://api.parse.com/1/users?foo=${encodeURIComponent(data.foo)}&bar=${encodeURIComponent(data.bar)}`, {
  method: "GET",
  headers: headers,   
})

是的,你应该,在 JS 中有一些 类,可以帮助你一个方便的是 https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

例如如果你在 javascript 对象中有参数,就说

let params = {one: 'one', two: 'two'}

你可以说这个函数

let queryString = new URLSearchParams()
for(let key in params){
  if(!params.hasOwnkey())continue
  queryString.append(key, params[key])
}

然后您可以通过说

来获得格式良好的查询字符串
queryString.toString()

已接受的答案有效,但如果您的参数多于一个,则无法概括。我建议使用以下方法,它也处理数组参数:

let route = 'http://test.url.com/offices/search';
if (method == 'GET' && params) {
  const query = Object.keys(params)
    .map((k) => {
      if (Array.isArray(params[k])) {
        return params[k]
          .map((val) => `${encodeURIComponent(k)}[]=${encodeURIComponent(val)}`)
          .join('&');
      }

      return `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`;
    })
    .join('&');

  route += `?${query}`;
}

简答

只需将值代入 URL,如下所示:

const encodedValue = encodeURIComponent(someVariable);
fetch(`https://example.com/foo?bar=${encodedValue}`);

更长的答案

是的,您只需要自己将查询字符串添加到 URL。你应该小心转义你的查询字符串参数,虽然 - 不要只是构造一个 URL like

`https://example.com/foo?bar=${someVariable}`

除非您确信 someVariable 绝对不包含任何 &= 或其他特殊字符。

如果您在 React Native 之外使用 fetch,您可以选择使用 URLSearchParams. However, React Native does not support URLSearchParams. Instead, use encodeURIComponent.

对查询字符串参数进行编码

例如:

const encodedValue = encodeURIComponent(someVariable);
fetch(`https://example.com/foo?bar=${encodedValue}`);

如果您想将键和值的对象序列化为查询字符串,您可以创建一个实用函数来执行此操作:

function objToQueryString(obj) {
  const keyValuePairs = [];
  for (const key in obj) {
    keyValuePairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
  }
  return keyValuePairs.join('&');
}

... 并像这样使用它:

const queryString = objToQueryString({
    key1: 'somevalue',
    key2: someVariable,
});
fetch(`https://example.com/foo?${queryString}`);

我对 Mark Amery's 的答案做了一个小重复,这将通过 Airbnb 的 eslint 定义,因为现在很多团队似乎都有这个要求。

function objToQueryString(obj) {
  const keyValuePairs = [];
  for (let i = 0; i < Object.keys(obj).length; i += 1) {
    keyValuePairs.push(`${encodeURIComponent(Object.keys(obj)[i])}=${encodeURIComponent(Object.values(obj)[i])}`);
  }
  return keyValuePairs.join('&');
}

我处理这个的简单函数:

/**
 * Get query string
 *
 * @param   {*}   query   query object (any object that Object.entries() can handle)
 * @returns {string}      query string
 */
function querystring(query = {}) {
  // get array of key value pairs ([[k1, v1], [k2, v2]])
  const qs = Object.entries(query)
    // filter pairs with undefined value
    .filter(pair => pair[1] !== undefined)
    // encode keys and values, remove the value if it is null, but leave the key
    .map(pair => pair.filter(i => i !== null).map(encodeURIComponent).join('='))
    .join('&');

  return qs && '?' + qs;
}

querystring({one: '#@$code', two: undefined, three: null, four: 100, 'fi##@ve': 'text'});
// "?one=%23%40%24code&three&four=100&fi%23%23%40ve=text"
querystring({});
// ""
querystring('one')
// "?0=o&1=n&2=e"
querystring(['one', 2, null, undefined]);
// "?0=one&1=2&2" (edited)

这是一个 es6 方法

const getQueryString = (queries) => {
    return Object.keys(queries).reduce((result, key) => {
        return [...result, `${encodeURIComponent(key)}=${encodeURIComponent(queries[key])}`]
    }, []).join('&');
};

这里我们接收一个形状为 key: param 的查询对象 我们迭代并减少这个对象的键,构建一个编码查询字符串数组。 最后我们做一个连接和 return 这个可附加的查询字符串。