react在axios成功后,执行this.setState

在axios的then中,this并不代表react组件,因此this.setState将执行异常:this is not defined

解决方法一 通过提前将this声明为变量

let ts = this;//在axios中setState方法一

axios.request({
            headers:{  //非必须
                "Content-Type":"application/x-www-form-urlencoded"
},
            url:Url,
            params:Params
        })
        .then(function (response) {
            let data =response.data
            console.log(data.name);

            ts.getData(data.name);
          })
          .catch(function (error) {
            console.log(error);
          });
    }

    getData(newName){
        this.setState({
            argName: newName
        });
    }

 

解决方法二 通过箭头函数

axios.request({
            headers:{  //非必须
                "Content-Type":"application/x-www-form-urlencoded"
},
            url:Url,
            params:Params
        })
        .then(aaa => this.setState({ //在axios中setState方法二
              argName:aaa.data.name
          }))
          .catch(function (error) {
            console.log(error);
          });
    }

axios.request({
            headers:{  //非必须
                "Content-Type":"application/x-www-form-urlencoded"
},
            url:Url,
            params:Params
        })
        .then((response) => {

            this.setState({ //在axios中setState方法三
                      argName:response.data.name
                  })
        })
          .catch(function (error) {
            console.log(error);
          });
    }

 

 

 

参考:https://blog.csdn.net/hj7jay/article/details/69230036

posted @ 2022-05-15 09:03  阿日斯兰  阅读(246)  评论(0编辑  收藏  举报