React Native - 使用AsyncStorage将数据存储在另一个屏幕中

问题描述 投票:0回答:2

我正在尝试使用AsyncStorage在我的应用程序中存储一些数据,但事情就是每当我提交数据然后导航到第二个屏幕(应该存储数据)时它就是空的。

navigation button

SendOrder Screen

这是我的代码

SendOrder.js

import Settlement from './Settlement';

export default class SendOrder extends React.Component {

state = {
    text: '',
    storedValue: '',
}

onSave = async () => {
    const { text } = this.state

    try {
        await AsyncStorage.setItem(key, text);
        Alert.alert('Saved', 'Successful');
    } catch (error) {
        Alert.alert('Error', 'There was an error.')
    }
}

onChange = (text) => {
    this.setState({ text });
}

  render() {
    return (
      <View>
        <View>
            <Text>- Noter -</Text>
        </View>
        <View>
            <TextInput
                onChangeText = {this.onChange}
                value = { this.state.text }>
            </TextInput>
        </View>
        <TouchableOpacity onPress = { this.onSave }>
            <Text style = { styles.addButtonText }> + </Text>
        </TouchableOpacity>    
      </View>
    );
  }
}

Settlement.js

import SendOrder from './SendOrder';
const key = '@MyApp:key';

export default class Settlement extends React.Component {

    state = {
        text: '',
        storedValue: '',
    }

    componentWillMount() {
        this.onLoad();
    }

    onLoad = async () => {
        try {
            const storedValue = await AsyncStorage.getItem(key);
        } catch (error) {
            Alert.alert('Error', 'There was an error.')
        }
    }

  render() {
      const { storedValue, text } = this.state;
    return (
        <View>
            <Text>{storedValue}</Text>
            <View>
                <TouchableOpacity onPress = {this.onLoad}>
                    <Text>Load Data</Text>
                </TouchableOpacity>
            </View>
        </View>
    );
  }
}
javascript react-native asyncstorage
2个回答
0
投票

你需要将storedValue存储到onLoad内的状态,就像

onLoad = async () => {
    try {
        const storedValue = await AsyncStorage.getItem(key);
        this.setState({ storedValue });
    } catch (error) {
        Alert.alert('Error', 'There was an error.')
    }
}

希望这会有所帮助!


0
投票

更改此行“await AsyncStorage.setItem(key,text);”to“await AsyncStorage.setItem('key',text);”键的名称应该是字符串,因此它应该在单引号中。

并将此行“const storedValue = await AsyncStorage.getItem(key);”更改为“const storedValue = await AsyncStorage.getItem('key');”调用的set键的名称应为string,因此它应该在单引号。

您设置的键是不同的,您获得的键是不同的

© www.soinside.com 2019 - 2024. All rights reserved.