简体   繁体   English

从回调内部访问查询变量

[英]Accessing the query variable from within callback

Take the following example: 请看以下示例:

getOptions() {

  let options = {};

  if (this.props.location.hasOwnProperty('query')) {

    const query = this.props.location.query;

    const queriesMap = {
      'createdBy': 'createdBy',
      'state': 'state',
      'created_from': 'created_at[from]',
      'created_to': 'created_at[to]'
    };

    Object.keys(query).map(function(key) {

      if(queriesMap.hasOwnProperty(key)) {
        options = Object.assign(options, { queriesMap[key]: query[key] });
      }
    });
  }

  return options;
}

I'm using the queriesMap object to map url parameters to build a new url to call an API. 我正在使用queriesMap对象来映射URL参数,以建立一个新的URL来调用API。 The problem is that query is undefined when I'm trying to access it from within the .map callback. 问题是,当我尝试从.map回调中访问query时,该query是未定义的。

How do I access the query variable? 如何访问query变量?

Looks like you are missing a [] around queriesMap[key] . 像你看起来是缺少[]围绕queriesMap[key] So it should be options = Object.assign(options, { [queriesMap[key]]: query[key] }); 因此应该是options = Object.assign(options, { [queriesMap[key]]: query[key] }); .

Also, you could just do options[queriesMap[key]] = query[key] rather than Object.assign 另外,您可以只执行options[queriesMap[key]] = query[key]而不是Object.assign

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM