javascript - Reactjs var未在条件内定义
问题描述
我有一个奇怪的问题,我修改了一个工作函数:
const reqBody = { bio: this.state.infoContent };
const cfg = { headers: { 'Accept': 'application/json','Content-Type': 'application/json', 'Authorization': this.store.user.token } };
axios.post(endpoint.users+'/profilesetdata', reqBody, cfg)
.then((result) => {
//...
})
.catch((err) => {
//...
})
对此:
// the condition is the difference
if ( type == 'bio' ){
const reqBody = { bio: this.state.infoContent };
}else{
const reqBody = { bio: this.state.infoContent };
}
const cfg = { headers: { 'Accept': 'application/json','Content-Type': 'application/json', 'Authorization': this.store.user.token } };
axios.post(endpoint.users+'/profilesetdata', reqBody, cfg)
.then((result) => {
//...
})
.catch((err) => {
//...
})
现在发生了一件奇怪的事情,在第一个版本中代码正常工作,在第二个版本中, reqBody 中的条件导致了这个错误:
'reqBody' 未定义 no-undef
现在,有可能在条件之前执行了 axios 代码吗?好的 js 是异步的,但这种行为似乎很奇怪,有人可以帮助我理解为什么会发生这种情况?
解决方案
这是因为您reqBody
在 if-else 块中定义了变量。它在该范围之外将不可用。您需要在公共范围内定义它,以便函数中的其他逻辑可以访问它。
let reqBody;
if ( type == 'bio' ){
reqBody = { bio: this.state.infoContent };
}else{
reqBody = { bio: this.state.infoContent };
}
const cfg = { headers: { 'Accept': 'application/json','Content-Type': 'application/json', 'Authorization': this.store.user.token } };
axios.post(endpoint.users+'/profilesetdata', reqBody, cfg)
.then((result) => {
//...
})
.catch((err) => {
//...
})
推荐阅读
- bash - 如何在bash中将动态脚本更改为静态脚本?
- c++ - 按下输入键且没有用户输入时捕获异常
- php - Laravel 8 - 在现有布局中包含刀片布局
- javascript - 未捕获的错误:引发了跨域错误。React 无法访问 React Js 开发中的实际错误对象
- php - 如果购物车中的产品类别需要在结帐时注册 Woocommerce
- symbolic-math - 用数字代替参与微分的变量
- postgresql - PostgreSQL 在函数内调用 WITH 表
- python-3.x - Chrome 浏览器在测试运行后自动关闭
- javascript - 如何过滤从我的 HTML 页面上的 URL 收到的数据
- postgresql - 按偏移的日期范围分组时间戳