How to keep React component state between mount/unmount?

后端 未结 8 1640
心在旅途
心在旅途 2020-12-12 18:15

I have a simple component that maintains an internal state. I have another component that toggles whether or not <

8条回答
  •  感情败类
    2020-12-12 18:28

    Hmm, you could use localStorage, or AsyncStorage if React Native.

    React Web

    componentWillUnmount() {
      localStorage.setItem('someSavedState', JSON.stringify(this.state))
    }
    

    Then later that day or 2 seconds later:

    componentWillMount() {
      const rehydrate = JSON.parse(localStorage.getItem('someSavedState'))
      this.setState(rehydrate)
    }
    

    React Native

    import { AsyncStorage } from 'react-native'
    
    async componentWillMount() {
      try {
        const result = await AsyncStorage.setItem('someSavedState', JSON.stringify(this.state))
        return result
      } catch (e) {
        return null
      }
    }
    

    Then later that day or 2 seconds later:

    async componentWillMount() {
      try {
        const data = await AsyncStorage.getItem('someSavedState')
        const rehydrate = JSON.parse(data)
        return this.setState(rehydrate)
      } catch (e) {
        return null
      }
    }
    

    You could also use Redux and pass the data into the child component when it renders. You might benefit from researching serializing state and the second parameter of the Redux createStore function which is for rehydrating an initial state.

    Just note that JSON.stringify() is an expensive operation, so you should not do it on keypress, etc. If you have concern, investigate debouncing.

提交回复
热议问题