【问题标题】:How to set value to a state variable inside a function in react如何在反应中为函数内的状态变量设置值
【发布时间】:2020-08-01 19:12:52
【问题描述】:

我收到一个后端响应,以使用 Axios 获取驱动程序详细信息,并且在收到该响应后,我想获取驱动程序的名称和地址。为此,我尝试将值设置为状态变量但无法分配,并且我尝试将值分配给数组状态变量并稍后访问它们但我无法获得结果

这是代码sn-p:

    getDriverInfo = async () => {
    var session = sessionStorage.getItem("session");
    var apiBaseUrl = "http://localhost:4000/api/";
    // var self = this;
    let det = [];
    var payload = {
      nic: session,
    };

    axios
      .post(apiBaseUrl + "driverDetails", payload)
      .then(async (response) => {
        console.log(response.data.success);

        if (response.data.code == 204) {
          console.log("Driver Data retrieved successfull");
          
          response.data.success.map((element) => {
            det.push(element);
            this.state.Ddetails.push(element);
            
          });
          
          console.log(det.length);
          console.log(this.state.Ddetails[0].dln);
           await this.setState({
             fname: this.state.Ddetails[0].fName,
             lname: this.state.Ddetails[0].lName,
           });
          
        } else {
          console.log("Details does not exists");
          alert("Details does not exist");
        }
      })
      .catch(function (error) {
        console.log(error);
      });
    
    console.log(det.length);
    this.state.Ddetails.map((item) => {
      console.log("Map");
      console.log(item.dln);
    });
    console.log(this.state.Ddetails.dln);
  };

【问题讨论】:

  • 使用 setState( { Ddetails : ....})
  • 直接改变 React 状态不是一个好习惯:this.state.Ddetails.push(element)。提问前请先阅读文档。
  • @EddwinPaz 那也没用

标签: reactjs dictionary axios setstate


【解决方案1】:

不要直接更新状态这是一种反常模式。

https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly

我稍微修改了你的代码。

getDriverInfo = async () => {
    var session = sessionStorage.getItem("session");
    var apiBaseUrl = "http://localhost:4000/api/";
    // var self = this;
    let det = [];
    var payload = {
      nic: session,
    };

    axios
      .post(apiBaseUrl + "driverDetails", payload)
      .then(async (response) => {
        console.log(response.data.success);

        if (response.data.code == 204) {
          console.log("Driver Data retrieved successfull");
          
          response.data.success.map((element) => {
            det.push(element);
            //Don't use like this ==> this.state.Ddetails.push(element);
          });
          this.setState({Ddetails:det},()=>{
              console.log(det.length);
              console.log(this.state.Ddetails[0].dln);
              this.setState(prevState=>{
                  console.log(det.length);
                  prevState.Ddetails.map((item) => {
                      console.log("Map");
                      console.log(item.dln);
                  });
                 console.log(prevState.Ddetails.dln);
                  return{
                      fname: prevState[0].fName,
                      lname: prevState[0].lName,
                  }
              });
          })
        } else {
          console.log("Details does not exists");
          alert("Details does not exist");
        }
      })
      .catch(function (error) {
        console.log(error);
      });
  };

【讨论】:

  • 谢谢,对不起,我是 React 新手。我已经尝试过您的代码,但出现以下错误:TypeError: Cannot read property 'fName' of undefined 348 | }); 349 | console.log(prevState.Ddetails.dln); 350 |返回 { > 351 | fname: prevState[0].fName, | ^ 352 | lname: prevState[0].lName, 353 | };第354章});
  • 学习新东西总是感觉很好!关于错误,您可能需要稍微调试一下。我通过查找修改了您的代码,但对于数据,我不确定您从 API 获得的形状或形式。可能会截取您的数据有助于回答。
【解决方案2】:
this.state = {
   name: 'mickey',
   lastName: 'mouse',
};

const display = () => {
  // wont work
  console.log(this.state.name, this.state.lastName);
}

function display() {
    // will work
    console.log(this.state.name, this.state.lastName);
}

如您所见,箭头函数不适用于 (this)

【讨论】:

    猜你喜欢
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 2017-05-08
    • 2020-02-22
    • 1970-01-01
    相关资源
    最近更新 更多