检查状态为真还是假

时间:2019-10-01 02:45:16

标签: javascript reactjs

我想检查状态为true还是false,如果为true,我将数据发送给模式 所以我想在setState完成更新后执行一个函数 这是我的代码:

getPriceData = () => {
    if(this.state.visibleModal){
    const id = this.props.product._id;
    DataController.getProduct(id).then(
        response =>
        this.setState({
            product: response,
            buyingPrice: response.price
        })
    );
    }        
}


<Button title='ADD TO CART' id={_id}
    buttonStyle={{ backgroundColor: 'darkgreen', marginRight: 10 }}
    containerStyle={{ width: 120}}
    onPress={this._toggleModal&&this.getPriceData}/>

2 个答案:

答案 0 :(得分:1)

React中的

this.setStateasynchronous。因此,您可以在setState中定义一个回调函数来处理,例如:

this.setState({
    product: response,
    buyingPrice: response.price
}, () => {
    // here, your state updated
    console.log('state updated: ', this.state)

})

答案 1 :(得分:0)

您可以尝试使用componentDidUpdate()

componentDidUpdate(prevProps, prevState) {
  if (!prevState.visibleModal && this.state.visibleModal) {
    this.getPriceData();
  }
}

getPriceData = () => {
  const id = this.props.product._id;
  DataController.getProduct(id).then(
      response =>
      this.setState({
          product: response,
          buyingPrice: response.price
      })
  );      
}

...

<Button 
  title='ADD TO CART' 
  id={_id}
  buttonStyle={{ backgroundColor: 'darkgreen', marginRight: 10 }}
  containerStyle={{ width: 120}}
  onPress={this._toggleModal}
/>