【问题标题】:Is it ok to import variables and use them inside of a function?可以导入变量并在函数内部使用它们吗?
【发布时间】:2018-08-09 18:35:26
【问题描述】:

我正在 React 中使用 Google Maps API 进行试验,并且我有这个函数可以在检查 API 数据是否被正确检索后创建信息窗口以绑定到标记:

createInfoWindow( marker, infoWindow ) {
    fetchData ? infoWindow.setContent( infoWindowContent ) : 
    infoWindow.setContent( infoWindowError );
    infoWindow.open( map, marker );
  }

现在,不要在 .setContent() 方法中直接定义 infowindows 内容,如下所示:

infoWindow.setContent(
  '</div>' +
       '<h2>Title: ' + marker.title'</h2>' +
       '<p>Coords: ' + marker.position'</p>' + 
   '</div>'
 ) ...

我宁愿在另一个文件中定义内容,然后在方法内部导出常量,如下所示:

文件:InfoWindow.js

export const infoContent = `<div>...</div>`;

然后简单地说:

import { infoContent } from "./InfoWindow.js";   

infowWindow.setContent( infoContent ) ...

澄清一下,我想知道这样做是否是一个好习惯,因为我对 React 非常陌生,而且对 ES6 也不太了解。谢谢!

P.s.:不幸的是,我目前无法测试这是否会返回任何错误,但一般的“你不应该这样做,因为......”会这样做:)

【问题讨论】:

  • 但是infoContent 是一个实际的常量,还是它依赖于一些变量(即marker)?如果是这样,您可以导出一个名为 getInfoContent 的函数,该函数接受该参数并返回一个字符串。
  • 您好,谢谢您的回复!目前它是一个保存 HTML 内容的常量,我想知道是否可以保持与其他变量的关系(marker 就是其中之一)。我想我明白了你的意思,这是有道理的。您能否用正式的答案详细说明一下?谢谢

标签: javascript reactjs google-maps export create-react-app


【解决方案1】:

绝对鼓励分离 HTML 内容以保持 IMO 的可读性。我建议,让您通过 marker 是使用 getter 实用程序函数,并将其导出:

export function getInfoContent({ title, position }) {
  return `…` // HTML content, you can use title and position from marker here
}

然后调用getter并传入marker

infoWindow.setContent(getInfoContent(marker))

我相信这比内联 HTML 模板文字更具可读性,并将它们解耦,使其对读者更具声明性。还有关于你的三元表达式的旁注:

fetchData ? infoWindow.setContent( infoWindowContent ) : 
infoWindow.setContent( infoWindowError );

总的思路是不用条件运算符来执行两个不同的调用,而是使用运算符来选择传递的表达式:

infoWindow.setContent(fetchData ? infoWindowContent : infoWindowError);

【讨论】:

  • 太棒了,感谢您阐明如何正确使用三元组。
猜你喜欢
  • 1970-01-01
  • 2019-06-03
  • 2013-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多