首页 > 解决方案 > 检查状态是真还是假

问题描述

我想检查状态是真还是假,如果为真,我会将数据发送到模态,所以我想在 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}/>

标签: javascriptreactjs

解决方案


this.setState在 React 中是asynchronous. 所以你可以在 setState 中定义一个回调函数来处理:

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

})

推荐阅读