0Pricing
React Native Academy · 课时

构建持久化设置屏幕

创建包含通知和深色模式切换项的设置屏幕,将每项设置持久化到 AsyncStorage,并在应用启动时恢复偏好。

构建持久化设置屏幕 是 CoddyKit 上的免费 React Native Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 React Native Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 React Native Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What a Persistent Settings Screen Does

A persistent settings screen lets users configure app preferences — such as dark mode, notification preferences, or language — and have those preferences survive app restarts. The settings are saved to AsyncStorage when changed and loaded back on startup. This is one of the most common patterns in any production React Native app.

Defining the Settings State

Start by defining a TypeScript interface for your settings object and a DEFAULT_SETTINGS constant used when no saved settings exist (first launch). Keeping defaults in a constant makes it easy to fall back safely and to reference the initial shape in type guards and migration logic.

interface Settings {
  darkMode: boolean;
  notificationsEnabled: boolean;
  fontSize: 'small' | 'medium' | 'large';
}

const DEFAULT_SETTINGS: Settings = {
  darkMode: false,
  notificationsEnabled: true,
  fontSize: 'medium',
};

const SETTINGS_KEY = 'app_settings';

Loading Settings on Screen Mount

In a useEffect with an empty dependency array, read the settings from AsyncStorage, parse the JSON, and place the result in component state. Show an ActivityIndicator while loading so the user does not see a momentary flash of default values before the real settings appear.

const [settings, setSettings] = React.useState<Settings>(DEFAULT_SETTINGS);
const [loading, setLoading] = React.useState(true);

useEffect(() => {
  async function loadSettings() {
    const json = await AsyncStorage.getItem(SETTINGS_KEY);
    if (json) {
      setSettings({ ...DEFAULT_SETTINGS, ...JSON.parse(json) });
    }
    setLoading(false);
  }
  loadSettings();
}, []);

Saving Settings When They Change

Create a helper function that merges the new setting into the current settings object and writes the result to AsyncStorage. Call this function from each UI control's change handler so settings are saved immediately after every user interaction. There is no need for a separate 'Save' button for a settings screen.

async function updateSetting<K extends keyof Settings>(key: K, value: Settings[K]) {
  const updated = { ...settings, [key]: value };
  setSettings(updated);
  await AsyncStorage.setItem(SETTINGS_KEY, JSON.stringify(updated));
}

Rendering the Dark Mode Toggle

Use React Native's Switch component for boolean settings. Bind its value prop to the state and call updateSetting in onValueChange. The UI updates instantly via state while AsyncStorage saves in the background, giving a responsive feel without waiting for the write to complete.

<View style={styles.row}>
  <Text style={styles.label}>Dark Mode</Text>
  <Switch
    value={settings.darkMode}
    onValueChange={(value) => updateSetting('darkMode', value)}
    trackColor={{ false: '#ccc', true: '#6200ee' }}
    thumbColor={settings.darkMode ? '#fff' : '#f4f3f4'}
  />
</View>

Rendering a Notification Toggle

Add a second Switch row for the notifications setting following the same pattern. Reusing the same updateSetting helper keeps the code DRY — you only change the key argument to target a different setting. This pattern scales to any number of boolean settings without duplicating save logic.

<View style={styles.row}>
  <Text style={styles.label}>Notifications</Text>
  <Switch
    value={settings.notificationsEnabled}
    onValueChange={(value) => updateSetting('notificationsEnabled', value)}
  />
</View>

Font Size Picker with Pressable Options

For an enum setting like font size, render a row of Pressable buttons, one for each option. Highlight the currently selected option with a different background color. Tapping a button calls updateSetting with the new value. This creates a compact, accessible selection control without a full dropdown.

const fontSizes: Settings['fontSize'][] = ['small', 'medium', 'large'];

<View style={styles.row}>
  <Text style={styles.label}>Font Size</Text>
  <View style={styles.optionRow}>
    {fontSizes.map((size) => (
      <Pressable
        key={size}
        onPress={() => updateSetting('fontSize', size)}
        style={[
          styles.option,
          settings.fontSize === size && styles.optionSelected,
        ]}
      >
        <Text>{size}</Text>
      </Pressable>
    ))}
  </View>
</View>

Applying Settings Globally with Context

For dark mode to affect the entire app, the settings must be shared globally. Load settings at the app root (in App.tsx) and store them in a SettingsContext. Any screen that needs the current theme can read from context instead of loading from AsyncStorage every time. Only the root loads from storage once on startup.

// App.tsx
const [settings, setSettings] = React.useState<Settings>(DEFAULT_SETTINGS);

useEffect(() => {
  loadSettings().then(setSettings);
}, []);

return (
  <SettingsContext.Provider value={{ settings, updateSetting }}>
    <NavigationContainer theme={settings.darkMode ? DarkTheme : DefaultTheme}>
      <AppNavigator />
    </NavigationContainer>
  </SettingsContext.Provider>
);

Reset to Defaults Button

Add a 'Reset to Defaults' button at the bottom of the settings screen. When tapped, it calls AsyncStorage.removeItem to erase the saved settings and resets the local state to DEFAULT_SETTINGS. Confirm the action with an Alert before applying the reset, as it is a potentially destructive operation.

function handleReset() {
  Alert.alert('Reset Settings', 'Restore all settings to their defaults?', [
    { text: 'Cancel', style: 'cancel' },
    {
      text: 'Reset',
      style: 'destructive',
      onPress: async () => {
        await AsyncStorage.removeItem(SETTINGS_KEY);
        setSettings(DEFAULT_SETTINGS);
      },
    },
  ]);
}

Testing Persistence Across Restarts

To verify your settings actually persist, change a setting, close the app completely (not just background it), reopen it, and check that the changed value is shown. In Expo Go you can test this with a force-close. In a development build, shake the device to access the dev menu and reload to simulate a fresh start while keeping AsyncStorage data.

Complete Settings Screen Structure

Here is the full structure of a settings screen combining all the patterns from this lesson. The screen loads settings on mount, renders toggles and pickers that call updateSetting, applies styles that honor the dark mode setting, and includes a reset button at the bottom. This template can be customized for any app's specific preferences.

export default function SettingsScreen() {
  const [settings, setSettings] = React.useState<Settings>(DEFAULT_SETTINGS);
  const [loading, setLoading] = React.useState(true);

  useEffect(() => { loadSettings().then((s) => { setSettings(s); setLoading(false); }); }, []);

  if (loading) return <ActivityIndicator />;

  return (
    <ScrollView style={[styles.container, settings.darkMode && styles.dark]}>
      <SwitchRow label='Dark Mode' value={settings.darkMode}
        onChange={(v) => updateSetting('darkMode', v)} />
      <SwitchRow label='Notifications' value={settings.notificationsEnabled}
        onChange={(v) => updateSetting('notificationsEnabled', v)} />
      <FontSizeRow value={settings.fontSize}
        onChange={(v) => updateSetting('fontSize', v)} />
      <Button title='Reset to Defaults' onPress={handleReset} color='red' />
    </ScrollView>
  );
}

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: loading on mount with useEffect restores settings from AsyncStorage before the screen renders, a single updateSetting helper merges changes and writes to AsyncStorage for any settings key, and sharing settings via Context makes preferences like dark mode available throughout the entire app. Next up we explore clearing storage and migration strategies.

常见问题解答

「构建持久化设置屏幕」课时是免费的吗?

是的 — 「构建持久化设置屏幕」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 React Native Academy 课程的其余内容,请升级到 CoddyKit PRO。 React Native Academy 课程共包含 4 节课。

「构建持久化设置屏幕」这节课中我会学到什么?

创建包含通知和深色模式切换项的设置屏幕,将每项设置持久化到 AsyncStorage,并在应用启动时恢复偏好。 你通过在浏览器中直接运行的动手代码来练习 React Native Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 React Native Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 React Native Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「构建持久化设置屏幕」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 React Native Academy 课中编写并运行代码吗?

能。每节 React Native Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 AsyncStorage 读写数据
  2. 存储并解析 JSON 对象
  3. 构建持久化设置屏幕
  4. 清除存储与迁移策略
← 返回 React Native Academy