javascript - react promise : TypeError: Cannot read property 'then' of undefined

标签 javascript jquery reactjs promise es6-promise

我需要在我的 API 上发布一些内容。 我有这个功能可以正常工作:

TradeContainer.js:

callApi(action){
  var actionInfo = {
      user_id: this.props.currentUser.id,
      action: action
  }

  fetch('http://localhost:3000/actions', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(actionInfo)
  })
  .then(res => res.json())
  .then(data => console.log(data))
 }

我想将 fetch() 移动到另一个文件,我从那里进行所有 API 调用。在那个文件中,我已经有几个获取函数(使用 get 方法)并且它们工作正常。 但是当我将这个带有 post 方法的 fetch() 移动到那个文件时,我得到一个错误:

TypeError: Cannot read property 'then' of undefined

我的代码:

TradeContainer.js:

import { saveAction } from '../components/apiCalls.js'

callApi(action){
  var actionInfo = {
      user_id: this.props.currentUser.id,
      action: action
  }

   //this is fetch() function that i moved to apiCalls.js file. 
   //And this two lines of code throw an error.
  saveAction(actionInfo)
  .then(data => console.log(data))
 }

apiCalls.js

export function saveAction(actionInfo){
  fetch('http://localhost:3000/actions', {
   method: 'POST',
   headers: {
   'Accept': 'application/json',
   'Content-Type': 'application/json'
   },
   body: JSON.stringify(actionInfo)
  })
  .then(res => res.json())
}

.then(res => res.json()) 返回“ok”和 200。 但是 saveAction(actionInfo) 返回 undefined。怎么会?

最佳答案

saveAction 函数不返回任何内容(特别是 - 不返回 promise),因此您不能在该函数上使用 then:

export function saveAction(actionInfo){
  fetch({
     ...
  })
  .then(res => res.json())
}

您可以返回 fetch(这是一个 promise ),然后您可以在该函数上使用 then:

export function saveAction(actionInfo){
  return fetch({
     ...
  })
  .then(res => res.json())
}

关于javascript - react promise : TypeError: Cannot read property 'then' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46014667/

相关文章:

java - 如何防止Applet跨网页卸载?

javascript - 如何在 react native Realm 中存储 [String] 或 [Int]

jQuery - 动态 div 高度等于整个窗口的高度

javascript - 从 <input> 值设置变量

javascript - 在 javascript 中是否有类似 PHP 的 preg_replace_callback() 的东西?

javascript - 仅当已可见时隐藏主体单击上的弹出框

javascript - 单击时不显示直通线?

css - 如何使用 ReactJS 和 Font-awesome 为半图标着色?

javascript - ReactJs 中可重用的模态

javascript - 如何将 Prop 传递给 React Navigation 导航器内的组件?