react-native save button status after changing screens

后端 未结 2 768
Happy的楠姐
Happy的楠姐 2021-01-20 23:39

I have 5 buttons [\"running\", \"riding\", \"reading\", \"coding\", \"Niuer\"] in my app and when I click on it, the button changes its color and displays the title on screen. I

相关标签:
2条回答
  • 2021-01-20 23:51

    There are a number of ways you could achieve this - one simple way might be to use the AyncStorage API to persist the state of your buttons so that it can be restored on return to this screen.

    So you could use this by:

    import { AsyncStorage } from "react-native"
    

    and then in _singleTapMultipleSelectedButtons_limited(interest) you could add the following to the end of the function:

    AsyncStorage.setItem('button_state',
         JSON.stringify(this.state.multipleSelectedDataLimited));
    

    finally, you'd add this method to your component to initialise your button state from any data that was persisted:

    componentDidMount() {
      try {
        // Fetch data from store if it exists
        AsyncStorage.getItem('button_state').then(data => {
    
          // If data present, try and parse it and restore button state from it
          if(data) {
            const multipleSelectedDataLimited = JSON.parse(data);
            this.setState({ multipleSelectedDataLimited })
          }          
        });
      }
      catch(err){
        console.log('Failed to load button state')
      }
    }
    

    Hope this helps!

    0 讨论(0)
  • 2021-01-21 00:09

    The best thing you can do is save your state in Redux and use redux-persist with that. You can also use AsyncStorage. I had similar scenario, I had to maintain state between two component navigating back and forth, I have used navigation params like this:

    Screen A:

    this.props.navigation.navigate('ScreenB', {
                  onPressScreenAFun: (params) => {
                    this.screenAFun(params),
                    ButtonState1: true // you can send multiple params
                  },
                })
    
    screenAFun = (ButtonState1) => {
     this.setState({buttonState1: ButtonState1})
    }
    

    Screen B:

        screenBFun = (params) => {
           const { onPressScreenAFun, ButtonState1 } = this.props.navigation.navigate.state.params
    
          onPressScreenAFun(ButtonState1)
          this.props.navigation.goBack()
        }
    
    0 讨论(0)
提交回复
热议问题