【问题标题】:calling a function from a const value从 const 值调用函数
【发布时间】:2020-11-24 14:28:31
【问题描述】:

我有一个如下所示的初始状态 const 项:

const INITIAL_STATE = {
  endPoint: { street: '', coordinates: [] }, //[13.3969, 52.5182]
  startingPoint: { street: '', coordinates: [] }, //[13.413215, 52.521918]
  favouritePoint: { street: '', coordinates: [] },
  favouriteLocations: {getFavouritePlaces()},
  // favouriteLocations: [
  //   {
  //     name: 'Zu Hause',
  //     street: 'Müllersweg',
  //     coordinates: [8.217462, 53.13975], //[8.258844, 53.119525],
  //   },
  //   {
  //     name: 'Büro',
  //     street: 'Philipp-Reis-Gang',
  //     coordinates: [8.258844, 53.119525], //[8.217462, 53.13975],
  //   },
  //   {
  //     name: 'KaffeeHaus',
  //     street: 'Cloppenburgerstr.',
  //     coordinates: [8.211, 53.113],
  //   },
  // ],
  addressesFoundList: [],
};

我尝试调用 favouriteLocations 的函数,而不是硬编码值,该函数将返回相同类型的对象。但是,目前这不会调用我的函数。

我的函数如下所示:

const getFavouritePlaces = () => {
return ...
}

稍后,我将在我的 redux 设置中使用这个初始状态。

【问题讨论】:

  • 那不是有效的javascript,我认为favouriteLocations: {getFavouritePlaces()},应该是:favouriteLocations: getFavouritePlaces(),
  • 这能回答你的问题吗? How to call a constant as a function name?
  • 即便如此,我也无法实现我想要的。因为我在函数内部使用了一个钩子,所以当我在这里调用它时,它给了我一个无效的钩子错误stackoverflow.com/questions/63248118/…@HMR

标签: javascript reactjs typescript react-native redux


【解决方案1】:

你应该这样声明它:

const getFavouritePlaces = () => {
       console.log('test');
    }
    
    const INITIAL_STATE = {
      favouriteLocations: getFavouritePlaces
    }

    INITIAL_STATE.favouriteLocations();

即使您的函数接收到如下变量,这也将起作用:

const getFavouritePlaces = (x) => {
  console.log(x);
};

const INITIAL_STATE = {
   favouriteLocations: getFavouritePlaces
}

INITIAL_STATE.favouriteLocations('test');

【讨论】:

  • 嗨@Jnl,我为你编辑了它......只需将(x:字符串)替换为(x)。如果它是打字稿代码,则可以使用 (x: string)。
  • 我的意思是因为我在函数内部使用了一个钩子,当我在这里调用它时,它给了我一个无效的钩子错误stackoverflow.com/questions/63248118/…
【解决方案2】:

如前所述,存在语法错误。

Alternativ 1 - 传播包含所需对象的函数:

const INITIAL_STATE = {
  favouriteLocations: {...getFavouritePlaces()}
};

Alternativ 2 - 运行将返回所需对象的函数:

const INITIAL_STATE = {
  favouriteLocations: getFavouritePlaces()
};

【讨论】:

【解决方案3】:

我认为你不需要函数调用的括号。

favouriteLocations: {getFavouritePlaces()}, 更改为favouriteLocations: getFavouritePlaces(),

【讨论】:

猜你喜欢
  • 2016-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-13
  • 2010-09-29
相关资源
最近更新 更多