从第二次获取结果

时间:2018-08-30 14:51:35

标签: javascript reactjs react-native asynchronous

我在做什么错?价格和文章不在第一次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>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

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