首页 > 解决方案 > 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 是异步的,但这种行为似乎很奇怪,有人可以帮助我理解为什么会发生这种情况?

标签: javascriptreactjs

解决方案


这是因为您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) => {
           //...
        })

推荐阅读