【发布时间】:2020-05-26 07:06:36
【问题描述】:
在我的组件中,它以 componentDidMount() 生命周期开始,该生命周期获取数据以显示在表格上。
componentDidMount() {
fetch(TABLE_DATA, {
//TABLE_DATA is a global variable that runs a callback which combines the rest of the variable
//to the url. It's mostly for deployment; an easy way to change urls back and forth.
credentials: 'include',
methods: 'GET',
headers: {
'Content-type': 'application/json',
},
})
.then(res => res.json())
.then(data=>{
this.setState({
tableData: data,
isLoaded: true
})
})
}
现在,当我想在同一个组件中的表单上提交一些信息时,出于某种原因,TABLE_DATA 变量会覆盖我正在获取的任何 url。 下面是提交表单的代码:
submitAccountToUser= e => {
e.preventDefault()
fetch(EXTRA_INFO, {
credentials: 'include',
methods: 'POST',
headers: {'Content-type': 'application/json'},
body: JSON.stringify({
'info':this.state.info
})
})
.then(res => console.log('res', res))
//doesn't get to this console.log. It stops on the line with "fetch(EXTRA_INFO
}
EXTRA_INFO 被覆盖为 TABLE_DATA。它在我的本地服务器/终端上显示在 TABLE_DATA url 处调用了一个“GET”方法。除了我的浏览器中的这个错误:
未处理的拒绝(TypeError):无法在“窗口”上执行“获取”:使用 GET/HEAD 方法的请求不能有正文。
这是有道理的,因为最初的 fetch 调用 (TABLE_DATA) 只是一个“GET”请求,不能有正文。但它甚至不应该获取该网址。 我通过查找语法错误并检查全局变量中的 url 来保持简单。但我不明白为什么它会完全忽略 EXTRA_INFO 的价值。
** 编辑 ** TABLE_DATA 和 EXTRA_INFO 获取其 api 的回调函数如下所示:
const TABLE_DATA = backend_route('/tableinfo')
const backend_route = (route) => {
const backend = 'http://127.0.0.1:5000'
return backend + route
}
【问题讨论】:
-
TABLE_DATA和EXTRA_INFO是如何定义的? (如果您担心,可以混淆 URL 的私人详细信息) -
@SebastianB。我编辑了帖子的底部以回答您的问题。希望这会有所帮助
标签: javascript reactjs api fetch lifecycle