无法立即更新状态

时间:2018-09-26 12:12:41

标签: reactjs react-native react-native-android react-navigation react-native-navigation

因此,当我单击Screen2上的“添加到购物车”按钮时,它会将articleToCart又称为cartArticle记录为空数组...仅当我返回到Screen1并再次在Screen2上再次按下“添加到购物车”按钮时,即使单击了添加到购物车按钮2次,也记录了具有一个项目的cartArticle数组2次...如何确保当我单击添加到购物车按钮时,它立即更新状态?我究竟做错了什么?我正在使用React Navigation v2。是否可以设置State谷底参数,并且立即将其延迟而不像这样呢?

class Screen1 extends Component {
  state = {
    articles: {
      article: [],
    },
  cartArticle: []
};

articleToCart = () => {
this.setState(prevState => {
  return {
    cartArticle:  prevState.cartArticle.concat(prevState.articles.article)
    };
  });
};


qrCodeOnReadHandler = ({ data }) => {
fetch(data)
  .then(response => response.json())
  .then(json => [
    console.log(json),
    this.setState({
      ...this.state,
      articles: {
        ...this.state.articles,
        article: json[0],
      }
    }),
    this.props.navigation.navigate("Screen2", {
      addToCartOnPress: () => this.articleToCart(),
      articleToCart: this.state.cartArticle,
    })
  ])
  .catch(err => {
    alert("Nesto ne valja. Pokusajte ponovo!");
    console.log(err);
  });
 };

render() {
  return (

    );
  }
}

第二屏

class Screen2 extends Component {

addToCartHandler = () => {
   const { navigation } = this.props;
   const articleToCart =navigation.getParam("articleToCart","Nedostupno");
    const add = navigation.getParam("addToCartOnPress", "Nedostupno");

console.log(articleToCart);

add();

};

goBackHandler = () => {
   this.props.navigation.goBack();
  };

 render() {
   return (
        <View style={styles.buttons}>
          <CustomButton color="#1DA1F2" onPress={this.goBackHandler}>
            Back
          </CustomButton>

          <CustomButton color="#1DA1F2" onPress={this.addToCartHandler}>
            Add to Cart
          </CustomButton>
    );
  }
}

2 个答案:

答案 0 :(得分:0)

在屏幕1的 qrCodeOnReadHandler

Fls_AddressType *

您将返回一个以函数为索引的数组。 尝试将其更改为此。

[
    console.log(json),
    this.setState({
      ...this.state,
      articles: {
        ...this.state.articles,
        article: json[0],
      }
    }),
    this.props.navigation.navigate("Screen2", {
      addToCartOnPress: () => this.articleToCart(),
      articleToCart: this.state.cartArticle,
    })
  ]

答案 1 :(得分:0)

setState是异步的,设置后不能立即读取值 ..但可以使用setState回调等等。像这样:

.then(json => {
  console.log(json)
  this.setState({
    ...this.state,
    articles: {
      ...this.state.articles,
      article: json[0],
    }
  }, () => {
    this.props.navigation.navigate("Screen2", {
      addToCartOnPress: () => this.articleToCart(),
      articleToCart: this.state.cartArticle,
    })
  })
})