【问题标题】:How to store the value of a variable in state immediately when set state is async设置状态为异步时如何立即将变量的值存储在状态中
【发布时间】:2021-10-26 21:10:10
【问题描述】:

我是新手,我正在尝试为客户存储状态值,我获取下拉列表值的代码是这样的:

handleChangeCC = customercode => {
    this.setState({ customercode });

    // var customer = customercode.map(o => o.label);
    // this.setState({ customer });

    var customer1 = customercode.label;
    this.setState({ customer: customer1 });

    console.log(`Option selected1:`, this.state.customer);
    this.getCustomerName();

    // console.log("Rec2:" + document.getElementById("CustomerCode").innerText);
  };

我在这个函数中运行函数 this.getCustomerName(),代码是这样的:

getCustomerName = () => {
    var Items = [];

    var code = this.state.customer;
    console.log('CustomerCode:' + code);
    axios.post('https://localhost:44303/api/observation/GetCustomerName?' + '&code=' + code).then(response => {
      //console.log('Value=' + response.data);
      console.log('Response=' + response.data);
      response.data.map(item => {
        var obj = new Object();

        // obj.label = desc;
        obj.label = item;

        Items.push(obj);
        //this.setState({ locations: response.data });
      });
      this.setState({ customerName: Items });

      console.log('customerName:' + this.state.customerName);
    });
  };

我在函数 getCustomerName 中设置 code= this.state.customer,我在 this.setState({ customer: customer1 }); 之后运行它在 handleChangeCC 函数中。

但是由于 this.setState 是一个异步函数,它不会立即更新状态,因此我将代码设为 null 并且我的 getCustomerName 函数不起作用

我该如何解决这个问题?有没有办法将一个函数的变量值传递给另一个函数。请帮忙

【问题讨论】:

    标签: javascript reactjs async-await


    【解决方案1】:

    在这种情况下,我会将customercode 传递给您的getCustomerName() 方法。 setState 需要一点时间,因此您的方法不会立即获得它的价值。您必须等待值处于状态,然后调用该方法。通过设置其状态将其传递给您的方法,您不必等待状态更新完成。

    另外,如果你刚刚学习 React,我会考虑使用基于函数的组件而不是遗留类组件,如果你有选择的话。

    【讨论】:

    • 您能否通过代码示例告诉我您的意思
    • 在您的handleChangeCC 中,您在setState({customercode}) 中,无法立即使用。因此,也将其传递给您的其他方法 getCustomerName(customercode),使用异步请求中的参数而不是不可用状态值。
    • 是的,谢谢
    【解决方案2】:

    是的,有几种技术可以获取最新值

    setState 中的第二个参数

    this.setState({ customerName: Items }, () => {
        console.log('latest value', this.state.customerName);
    });
    

    可以选择传递给 setState 的第二个参数是一个回调函数,它在 setState 完成并重新渲染组件后立即被调用。

    更多here

    异步方法

      updateA = async () => {
        this.setState({
          a: "test"
        });
        await (() => {})(); // or fetch or any async operation
        console.log(this.state.a);
      };
    

    请注意,这不是推荐的方法,但当前版本的 react 支持它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-03
      • 2017-06-16
      • 2014-09-23
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2016-08-27
      相关资源
      最近更新 更多