gpt4 book ai didi

javascript - 从第二次获取结果

转载 作者:行者123 更新时间:2023-12-03 01:14:07 24 4
gpt4 key购买 nike

我做错了什么?价格和文章在第一次二维码扫描时不会呈现,但从第二次、第三次开始......我猜测它与异步代码有关,但我看不到我需要做什么......有人可以帮助我吗请?提前告知!

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>
);
}
}

关于javascript - 从第二次获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52099968/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com