【发布时间】:2021-09-04 23:21:07
【问题描述】:
我已将 thunk 正确导入并安装在我的 index.js 文件中。我正在尝试设置一个操作,该操作将在进行提取时呈现加载页面,然后在 .then() 块内进行第二次提取。这是因为每次获取都需要从 rails 显示页面检索数据,然后使用该代码创建 JS 对象并将其添加到数组中。代码如下...
return (dispatch) => {
dispatch({type: 'LOAD_FIGURE'})
let movesLen = moves.length // Going to be either 2 or 3
if (movesLen == 2){
fetch(`http://localhost:3000/moves/show/${moves[0]}`) // Generate first move
.then(resp => resp.json())
.then(json => console.log(json)) // make this functional later
.then(fetch(`http://localhost:3000/moves/show/${moves[1]}`) // Generate the second move
.then(resp => resp.json())
.then(json => console.log(json)) // make this functional later
)
}
}
这只会返回以下错误
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
我不确定这里可能出了什么问题,因为此获取非常基本。我担心它与嵌套提取有关,但我两次收到错误的事实也让我认为,当它同时提取两者时,都返回相同的错误。
【问题讨论】:
-
我要检查的第一件事是 API 端点是否正确响应 - 在 devTools 中的网络选项卡中检查这一点。该错误通常表明正在接收和处理 HTML(或 XML),因此它会在响应的第一个位置找到
<。 -
与错误无关,但嵌套
.then()调用是代码异味。 Promises aren't just callbacks。创建它们是为了避免嵌套它们。 -
你说的很对,但我需要这个项目在一周内正常运行,所以我需要专注于功能,然后继续修复任何代码异味
标签: javascript ruby-on-rails json redux fetch