javascript - 从第二次获取 fetch 结果
问题描述
我究竟做错了什么?价格和文章不会在第一次 qr 扫描时呈现,而是从第二次、第三次…我猜它与异步代码有关,但我看不出我需要做什么…有人可以帮我吗请?提前Tnx!
export default class Qr extends Component {
state = {
price: [],
article: [],
};
qrCodeOnReadHandler = ({ data }) => {
let price = this.state.price;
let article = this.state.article;
fetch(data)
.then(response => response.json())
.then(json => [
console.log(json),
article.push(json[0]),
price.push(parseInt(json[4]))
]);
console.log(price);
console.log(article);
};
render() {
return (
<View style={{ flex: 1 }}>
<View style={styles.price}>
<Text style={styles.text}>Proizvod: {this.state.article}</Text>
</View>
<View style={styles.price}>
<Text style={styles.text}>Cena: {this.state.price}</Text>
</View>
</View>
);
}
}
解决方案
您正在直接修改状态。那是不行的。您应该改为调用 setState
export default class Qr extends Component {
state = {
price: [],
article: [],
};
qrCodeOnReadHandler = ({ data }) => {
fetch(data)
.then(response => response.json())
.then(json => [
console.log(json),
this.setState({
article: [...this.state.article, json[0]],
price: [...this.state.price, json[4]],
})
]);
};
render() {
return (
<View style={{ flex: 1 }}>
<View style={styles.price}>
<Text style={styles.text}>Proizvod: {this.state.article}</Text>
</View>
<View style={styles.price}>
<Text style={styles.text}>Cena: {this.state.price}</Text>
</View>
</View>
);
}
}
推荐阅读
- r - 在成对比较之后使用 p 值制作 heapmap
- node.js - Strapi 重建数据库模式 nodejs 更新招摇文档
- excel - Finviz.com 通过 VBA 抓取网页标头
- android - Kotlin 列表自行修改
- android - 带有 OpenCV 错误 dlopen 的 Android Studio 失败:找不到库“libopencv_java3415.so”
- firebase - 将表日历连接到 Firebase Flutter
- json - Json 数组上的 Laravel 关系
- python - 如何在 PYTHON 中从当月(EOMONTH 的 excel 版本)中找到当月的最后一天?
- swift - 连接到 SocketIO 时 Swift 中的长轮询请求错误
- firebase - Firebae 通知主题限制