在本机反应中我应该使用什么而不是 componentWillMount
In react native what should i use instead of componentWillMount
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) });
});}
我应该怎么做才能在呈现之前获取购物车商品??
有一个经验法则。您的旧代码(实现 componentWillMount
)是否有任何副作用?不,这只是一个初始化,您可以在 constructor
中进行。如果您需要执行副作用(例如 API 调用),您应该使用 componentDidMount
而不是
state = { cartItems : [] }
componentDidMount() {
AsyncStorage.getItem("CART", (err, res) => {
if (!res) this.setState({ cartItems: [] });
else this.setState({ cartItems: JSON.parse(res) });
});
}
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) });
});}
我应该怎么做才能在呈现之前获取购物车商品??
有一个经验法则。您的旧代码(实现 componentWillMount
)是否有任何副作用?不,这只是一个初始化,您可以在 constructor
中进行。如果您需要执行副作用(例如 API 调用),您应该使用 componentDidMount
而不是
state = { cartItems : [] }
componentDidMount() {
AsyncStorage.getItem("CART", (err, res) => {
if (!res) this.setState({ cartItems: [] });
else this.setState({ cartItems: JSON.parse(res) });
});
}