You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中使用AsyncStorage跨页面存储数据遇空值问题

Fixing AsyncStorage & Navigation Issue in Your React Native App

Hey, let's fix this step by step! I spot a few key issues in your code that are causing the empty Settlement page problem:


1. Missing key definition in SendOrder.js

You're using key in AsyncStorage.setItem(key, text) but never defined it in SendOrder.js. It needs to match the key you're using in Settlement.js (@MyApp:key).

2. No navigation to Settlement after saving data

Your onSave function only saves the data but doesn't navigate to the Settlement page. You need to add navigation logic here (assuming you're using React Navigation).

3. Settlement doesn't update state after fetching data

In your onLoad method, you successfully fetch storedValue but never update the component's state with it—so the page has no data to render.

4. Using deprecated lifecycle method

componentWillMount is deprecated in React; use componentDidMount instead for initial data fetching.


Fixed SendOrder.js

import React from 'react';
import { View, Text, TextInput, TouchableOpacity, Alert } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Settlement from './Settlement';

// Define the shared key here (or extract to a separate constants file)
const key = '@MyApp:key';

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');
      // Navigate to Settlement page after successful save
      this.props.navigation.navigate('Settlement');
    } 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}
            placeholder="Enter your note"
          />
        </View>
        <TouchableOpacity onPress={this.onSave}>
          <Text style={styles.addButtonText}> + </Text>
        </TouchableOpacity>
      </View>
    );
  }
}

// Don't forget your styles (you had styles.addButtonText referenced)
const styles = {
  addButtonText: {
    fontSize: 24,
    padding: 10,
    backgroundColor: '#eee',
    textAlign: 'center',
    marginTop: 10,
  }
};

Fixed Settlement.js

import React from 'react';
import { View, Text, TouchableOpacity, Alert } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import SendOrder from './SendOrder';

const key = '@MyApp:key';

export default class Settlement extends React.Component {
  state = {
    storedValue: '',
  }

  // Use componentDidMount instead of componentWillMount
  componentDidMount() {
    this.onLoad();
  }

  onLoad = async () => {
    try {
      const storedValue = await AsyncStorage.getItem(key);
      // Update state with the fetched value so it renders on the page
      this.setState({ storedValue });
    } catch (error) {
      Alert.alert('Error', 'There was an error.')
    }
  }

  render() {
    const { storedValue } = this.state;
    return (
      <View>
        <Text>Stored Note: {storedValue || 'No data saved yet'}</Text>
        <View style={{ marginTop: 20 }}>
          <TouchableOpacity onPress={this.onLoad}>
            <Text>Refresh Data</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

Extra Tips:

  • For better code organization, extract the shared key to a separate constants file (like constants/StorageKeys.js) so you don't repeat it across files.
  • Make sure your navigation setup correctly registers both SendOrder and Settlement screens (if using React Navigation).
  • Add a fallback message (like 'No data saved yet') so the page isn't completely empty when there's no stored data.

内容的提问来源于stack exchange,提问作者Violet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:05:17