【问题标题】:Show component only once in React or React Native using localstorage使用 localstorage 在 React 或 React Native 中仅显示一次组件
【发布时间】:2017-11-11 09:35:00
【问题描述】:

我有以下情况,我尝试使用 localstorge 仅显示一次屏幕组件。这让我精神崩溃。

App.js

...

constructor(props) {
    super(props);
    this.state = {
      isLoading: false,
    };
  }

  componentDidMount() {
    if (AsyncStorage.getItem('key')) {
      AsyncStorage.getItem('key', (value) => {
        this.setState({isLoading: value})
        Alert.alert(JSON.stringify(value))
      });
      AsyncStorage.setItem('key', JSON.stringify(true))
    }
  }

  render() {
    if (!this.state.isLoading) {
      return <Search />
    }
    return <Root />
    }

... 

【问题讨论】:

  • AsyncStorage 非常异步,您无法通过这种方式检查密钥的存在if (AsyncStorage.getItem('key')) {
  • 啊,有什么办法可以做到这一点吗?

标签: javascript reactjs react-native local-storage asyncstorage


【解决方案1】:

您需要稍微修改componentDidMount 实现并为组件的状态添加另一个标志

constructor() {
   ...
   this.state = {
      isLoaded: false,
      wasShown: false
   }
}

componentDidMount() {
   AsyncStorage.getItem('key') // get key
     .then(wasShown => {
         if(wasShown === null) { // first time 
           // we need to save key for the next time
           AsyncStorage.setItem('key', '"true"')
         }

         this.setState({isLoaded: true, wasShown})
      })
  }

render() {
  const { isLoaded, wasShown } = this.state

  // you can't tell if this component was shown or not render nothing
  if(!isLoaded) { return null }

  if(!wasShown) {
    return <Search />
  } 

  return <Root/>
}

顺便说一句,如果你在你的 babel 预设中包含 async/await 支持,你可以让这段代码更简单

async componentDidMount() {
   const wasShown = await AsyncStorage.getItem('key') // get key

   if(wasShown === null) {
     await AsyncStorage.setItem('key', '"true"')
   }

   this.setState({isLoaded: true, wasShown}
  }

【讨论】:

  • 这在逻辑上可能使用 redux 持久化吗?我可以使用 redux 设置值,但不知道如何处理获取 redux 中的键的存储方法 persist
  • MB。我从未使用过 redux-persist 包。
【解决方案2】:

在检查存储的价值时显示其他内容。获得值后,只需设置状态并显示您的屏幕。换句话说,你应该在确定你还没有显示屏幕之后才打开你的屏幕组件。

【讨论】:

    【解决方案3】:
    AsyncStorage.getItem('isShown').then((value) => {
          if(value == null){
            // Whatever you want to do just once.
            AsyncStorage.setItem('isShown', 'sth');
          }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-08
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 2023-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多