javascript - 检查状态是真还是假
问题描述
我想检查状态是真还是假,如果为真,我会将数据发送到模态,所以我想在 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}/>
解决方案
this.setState
在 React 中是asynchronous
. 所以你可以在 setState 中定义一个回调函数来处理:
this.setState({
product: response,
buyingPrice: response.price
}, () => {
// here, your state updated
console.log('state updated: ', this.state)
})
推荐阅读
- android - 我想用 WebView 在 Android Activity 中显示 pdf 文件,但是运行项目后什么都没有显示
- javascript - 单击 HTML 按钮运行 JSX 脚本
- c++ - 为模板类创建两个指针并使用当前选择的可能?
- r - 使用 if & 语句
- reactjs - 反应本机,无效尝试传播非无误实例
- c# - DropDownList 未在 MVC Razor .net 中显示 SelectedValue
- google-apps-script - 如何解决谷歌脚本的错误“getLastRow”?
- java - 如何摆脱 - “java.io.IOException:系统找不到指定的路径”
- r - 在 dplyr 1.0 中使用 tidyeval 一次汇总多个函数
- sql - 列名“total_counted”无效