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?
答案 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) });
});
}