首页 > 解决方案 > 从第二次获取 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>
    );
  }
}

标签: javascriptreactjsreact-nativeasynchronous

解决方案


您正在直接修改状态。那是不行的。您应该改为调用 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>
    );
  }
}


推荐阅读