小编Dog*_*oge的帖子

React - 单击按钮时从外部 API 函数获取

当用户单击按钮时,我试图从组件启动 API 调用。一个 URL 参数取决于用户在单击按钮之前选择的词。fetch 函数在一个外部函数中。当我在按钮单击时调用该函数并控制台记录结果时,它显示undefined,可能是因为该函数的异步性质。

如果我想将 fetch 响应放入App组件状态,我该如何解决这个问题?

import { fetchAPI } from '../fetchAPI';

export default class App extends Component {

constructor() {
    super();
    this.toggleButtonState = this.toggleButtonState.bind(this);
    state = { ... }
}

toggleButtonState() {
    let selectedWord = window.getSelection().toString();
    fetchAPI(selectedWord);
    // call the fetchAPI function and put the result into state
}

export function fetchAPI(param) {
    // param is a highlighted word from the user before it clicked the button
    fetch('https://api.com/?param=' + param)
    .then(function(result) { …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous fetch reactjs

6
推荐指数
1
解决办法
3万
查看次数

如何使用 moment.js 和 ES6 创建小时 + 分钟数组?

我正在尝试使用 moment.js 和 ES6 创建一天中间隔 30 分钟的一组小时。

例子: let hours = ["12:00 AM", "12:30 AM", "1:00 AM", "1:30 AM", ..., "11:30 PM"]

我已经有这个for功能了:

someFunction () {
  const items = []
  for (let hour = 0; hour < 24; hour++) {
    items.push(moment({ hour }).format('h:mm A'))
    items.push(moment({ hour, minute: 30 }).format('h:mm A'))
  }
  return items
}
Run Code Online (Sandbox Code Playgroud)

但我想让它更像 ES6。

我已经走到这一步了:

someFunction () {
  let timeSlots = new Array(24).fill().map((acc, index) => {
    let items = []
    items.push(moment( index ).format('h:mm A'))
    items.push(moment({ index, …
Run Code Online (Sandbox Code Playgroud)

javascript momentjs ecmascript-6

4
推荐指数
1
解决办法
8670
查看次数

Intl.NumberFormat 的指数表示法

我试图弄清楚是否有办法使用 Javascript 的Intl.NumberFormat()来创建平方米值。

\n

比如说,我想用它来创建一个像30 m\xc2\xb2该函数一样的值。页面上或任何使用 Google 的地方都没有指数示例。有可能吗?

\n

javascript

3
推荐指数
1
解决办法
1516
查看次数