React native API响应在ComponentDidMount中不可访问,但在render中我可以使用

React native API响应在ComponentDidMount中不可访问,但在render中我可以使用,react-native,React Native,嗨,我正在开发React本机应用程序。我正在使用Redux和Saga。我在componentDidMount中调用API async componentDidMount() { let data = this.props.navigation.getParam("returnProductData"); if (data) { console.log("Return Here"); this.props.getProductReturnAction(dat

嗨,我正在开发React本机应用程序。我正在使用Redux和Saga。我在componentDidMount中调用API

async componentDidMount() {
    let data = this.props.navigation.getParam("returnProductData");
    if (data) {
      console.log("Return Here");
      this.props.getProductReturnAction(data)
      this.setState({
        returnQty:parseInt(this.props.product.item_ordered)-parseInt(this.props.product.already_return_qty)
      });
      console.log(this.state.returnQty,"Return quty"); //coming undefined
      console.log(this.props.product, "product"); // undefined
      console.log(this.props.product.item_ordered); //undefined
    }
  }
我必须在componentDidMount中为returnQty设置状态。但是,这里无法访问该州。它在渲染方法中运行良好。我可以使用所有产品对象。但是,它在componentDidMount中是空的。我尝试使用async和Wait,但它不起作用

//调度方法

const mapDispatchToProps = dispatch => {
  return bindActionCreators(
    { getProductReturnAction, submitProductReturnAction },
    dispatch
  );
};
//道具

const mapStateToProps = state => {
  return {
    product: state.myOrdersReducer.returnProduct
  };
};

我无法找出错误,请帮助找出最佳解决方案。

当您通过redux/saga进行API调用时,您不能使用async Wait,因为框架将只发送一个操作并返回,为该操作注册的侦听器将被触发,然后在他们完成工作后,他们将发送一个新操作,并处理响应

上面解释的是一般情况

在您的场景中

  • 您正在调度由
    getProductReturnAction
    返回的操作,该操作将给出say
    GET\u PRODUCTS
    操作
  • 一个传奇将被注册为
    GET\u PRODUCTS
    ,比如说getProducts,这将被调用
  • 这将执行API调用,一旦收到响应,它将与产品数据一起发送
    GET\u PRODUCTS\u SUCCESS
  • 处理
    GET\u PRODUCTS\u SUCCESS
    的相应减速机将被调用,并更新
    returnProduct
    ,当您在组件中注册该减速机时,将调用渲染方法(当道具更改时),因此渲染方法中的产品数据可用
这是完全正确的。我看这里没有什么问题


由于数据在道具中可用,因此使用相同的u不需要再次进行设置状态。

实际上,我必须在文本框中显示剩余数量。因此,用户将从此处输入退货数量。当用户输入该值时,将在状态returnQty中设置该值。因此,我需要首先设置状态,以便从API响应向用户显示可用数量。您将从API
getProductReturnAction
获取剩余数量?是的,我正在获取。但是,最初我必须将其设置为与ReturnQuantity相同的状态,以便我可以使用。如果您从
getProductReturnAction
api获取If,那么您可以显示初始状态,您必须显示进度条,直到获得响应,然后在文本框中显示数量,没有其他选择。