简体   繁体   English

反应原生中的切换按钮

[英]Switch button in react-native

Hi I have a problem with the switch button in react-native.嗨,我在 react-native 中的开关按钮有问题。 I'm using it to toggle or not the activation of push notification.我正在使用它来切换或不激活推送通知。 The problem is that if I quit the application, the state of the switch is getting back to false, it's not saving the state ?问题是,如果我退出应用程序,开关的状态会变回 false,它没有保存状态? What am I doing wrong ?我究竟做错了什么 ?

Here is my code :这是我的代码:

constructor(props) {
    super(props)

    this.state = {
        switchValue:false
    }
}

toggleSwitch = (value) => {
    this.setState({switchValue: value})
    if(this.state.switchValue){
        console.log("Unsubscribed")
    } else {
        console.log("Subscribed")
    }
}

render() {
    return (
    <SafeAreaView>
        <ScrollView>
            <View style = {styles.view_container}>
                <Text style = {styles.titre}>Notifications</Text>
                <Text style = {{marginTop:9}}>Permet de recevoir des alertes lorsque de nouvelles vidéos sont disponibles.</Text>

                <View style = {{marginTop: 30, justifyContent:"center", alignContent:"center"}}>
                    <View style = {styles.row}>
                        <View style = {styles.row_infos}>
                            <Image source={require('../Images/couleurs/icons8-belier-100.png')} style = {styles.image}/>
                            <Text style = {{fontWeight:"bold", fontSize:16,lineHeight:16, color:"#7c4dff"}}>Bélier</Text>
                        </View>
                        <Switch
                            onValueChange = {this.toggleSwitchBelier}
                            value = {this.state.switchValueBelier}
                            trackColor={{false:'#000000', true:'#7c4dff'}}
                        />
                    </View>
                 </View>
              </View>
           </ScrollView>
        </SafeAreaView>      
)}       

When you quit your Application, all saved variables in the state will be "resetted".当您退出应用程序时,状态中所有保存的变量都将被“重置”。

If you would like to keep the state of the toggle button, i would recommend you to use the AsyncStorage , provided by expo.如果您想保持切换按钮的状态,我建议您使用AsyncStorage提供的AsyncStorage

See here: https://docs.expo.io/versions/v36.0.0/react-native/asyncstorage/请参阅此处: https : //docs.expo.io/versions/v36.0.0/react-native/asyncstorage/

Just set the item when the toggle-function is triggered like this:只需在触发切换功能时设置项目,如下所示:

import { AsyncStorage } from 'react-native';
AsyncStorage.setItem('buttonToggle', 'true');

And when you start the application again, load the current status from the AsyncStorage :当您再次启动应用程序时,从AsyncStorage加载当前状态:

const value = await AsyncStorage.getItem('buttonToggle');
if (!!value && value === 'true'){
 // Do whatever you like
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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