【问题标题】:In react native what should i use instead of componentWillMount在本机反应中,我应该使用什么来代替 componentWillMount
【发布时间】:2019-10-07 12:08:21
【问题描述】:

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) });
});}

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

【问题讨论】:

标签: reactjs react-native asyncstorage


【解决方案1】:

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

state = { cartItems : [] } 

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

【讨论】:

  • 对于组件已经挂载的情况,有时 navigation.navigate 不会进行全新的 api 调用,因此最好使用 navigation.push 使组件在堆栈顶部重新登录并制作全新的 api 调用或您想在其中执行的任何操作。
  • 注意,componentDidMount 这是获取初始数据的好地方。如果您的数据必须在 prop / state 更新时更改,那么您应该查看 componentDidUpdate
  • 正确,但有时 componentDidUPdate 是有风险的,因为如果处理不当会进入循环
  • 万一您遇到 Asyncstorage 问题,请将您的代码放在“async”函数中,并在 Asyncstorage.getItem() 之前使用 await,然后在 ComponentDidMount 中调用此函数
  • 所以如果我使用 flatlist 并且我想重新渲染 flatlist 以从 api 获取新数据,我应该使用 componentDidMount?可以举个例子吗
猜你喜欢
  • 2010-11-05
  • 2010-12-06
  • 2012-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
相关资源
最近更新 更多