我有一个带按钮的屏幕,用于选择游戏的玩家数量。单击这些按钮中的任何一个都会调用一个函数,将相应的数字传递给函数,将该数字存储在异步存储中,然后导航到下一个屏幕。见下面的代码:
//Example of the buttons:
<Text style={styles.text}>
How Many Players?
</Text>
<PrimaryButton
onPress={() => this.startRound(3)}
label="3"
>
</PrimaryButton>
<PrimaryButton
onPress={() => this.startRound(4)}
label="4"
>
</PrimaryButton>
//The function:
startRound = (num_players) => {
AsyncStorage.setItem('Num_Players', num_players);
this.props.navigation.navigate('player_names_screen');
}
在下一个屏幕上,如果我尝试使用AsyncStorage.getItem来获取此数字,那么我可以用它来做事情,我只是得到null。见下面的代码:
constructor (props) {
super(props);
this.state = {
get_players: null
}
}
componentWillMount = () => {
this.getNumPlayers();
var players = this.state.get_players;
alert(players);
}
getNumPlayers = async () => {
let players = await AsyncStorage.getItem('Num_Players');
this.setState({get_players: players});
}
我正在使用alert函数来查看使用AsyncStorage.getItem得到的结果,正如我之前所说,它显示为“null”。正如标题中所述,我已经从react-native-community安装了异步存储,并且使用了来自'@ react-native-community / async-storage'的导入AsyncStorage;“。
AsyncStorage无法存储整数值以将整数值转换为字符串
AsyncStorage.setItem('Num_Players', JSON.stringify(num_players));
要么
AsyncStorage.setItem('Num_Players', ''+num_players);
请检查一下
https://snack.expo.io/@vishal7008/convert-variable-stored-in-asyncstorage-then-state-to-number