简体   繁体   中英

react-native save button status after changing screens

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 am using this library: react-native-selectmultiple-button .

Say I clicked button "running", and "riding", these buttons will be highlighted and text will display on screen but when I change the screen to another page and come back to the previous screen button state is set back to default.

Below is my code:

const multipleData = ["running", "riding", "reading", "coding", "Niuer"];

export default class SimpleButton extends Component {
  constructor(props) {
    super(props);
    this.state = {
      multipleSelectedDataLimited: []
    };
  }

  render() {
    return (
      <View style={{paddingTop:200}}>
      <Text style={styles.welcome}>
        implement the multiple-select buttons demo by SelectMultipleButton
      </Text>
      <Text style={{ color: 'blue', marginLeft: 10 }}>
      I like {_.join(this.state.multipleSelectedDataLimited, ", ")}
      </Text>
        <View
          style={{
            flexWrap: "wrap",
            flexDirection: "row",
            justifyContent: "center"
          }}
        >
          {multipleData.map(interest => (
            <SelectMultipleButton
              key={interest}
              buttonViewStyle={{
                borderRadius: 10,
                height: 40
              }}
              textStyle={{
                fontSize: 15
              }}
              highLightStyle={{
                borderColor: "gray",
                backgroundColor: "transparent",
                textColor: "gray",
                borderTintColor: 'blue',
                backgroundTintColor: 'blue',
                textTintColor: "white"
              }}
              value={interest}
              selected={this.state.multipleSelectedDataLimited.includes(
                interest
              )}
              singleTap={valueTap =>
                this._singleTapMultipleSelectedButtons_limited(interest)
              }
            />
          ))}
        </View>
      </View>
    );
  }

  _singleTapMultipleSelectedButtons_limited(interest) {
    if (this.state.multipleSelectedDataLimited.includes(interest)) {
      _.remove(this.state.multipleSelectedDataLimited, ele => {
        return ele === interest;
      });
    } else {
      if (this.state.multipleSelectedDataLimited.length < 3)
        this.state.multipleSelectedDataLimited.push(interest);
    }
    this.setState({
      multipleSelectedDataLimited: this.state.multipleSelectedDataLimited
    });
  }
}

const styles = StyleSheet.create({
  welcome: {
    margin: 10,
    marginTop: 30,
    color: "gray"
  }
});

Is there a way I could keep the status of the buttons even after changing the screen?

Any advice or comments would be really appreciated. Thanks in advance!

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM