在本机反应中我应该使用什么而不是componentWillMount

时间:2019-10-07 12:08:21

标签: reactjs react-native asyncstorage

ComponentWillMount已重命名和不建议使用,不建议使用

  constructor(props) {
super(props);
this.state = {
  cartItems: []
};}


componentWillMount() {
AsyncStorage.getItem("CART", (err, res) => {
  if (!res) this.setState({ cartItems: [] });
  else this.setState({ cartItems: JSON.parse(res) });
});}

我应该怎么做才能在渲染之前获取cartItem?

1 个答案:

答案 0 :(得分:3)

有一个经验法则。您的旧代码(实现componentWillMount)是否有副作用?不,它只是一个初始化,您可以在constructor中进行初始化。如果您需要执行副作用(例如API调用),则应改用componentDidMount

state = { cartItems : [] } 

componentDidMount() {
    AsyncStorage.getItem("CART", (err, res) => {
        if (!res) this.setState({ cartItems: [] });
        else this.setState({ cartItems: JSON.parse(res) });
    });
}