0Pricing
React Native Academy · 课时

提升状态

将共享状态移至最近的公共祖先组件,并将值和更新回调作为 props 传给兄弟组件,使它们保持同步。

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

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

The Problem: Siblings Need Shared State

Imagine two sibling components that need to share a piece of data — for example, a search input component and a results list that filters based on that search query. If the search state lives inside the search input component, the results list has no way to access it. Neither sibling can see each other's state directly. The solution is to lift the state up to the nearest common ancestor — the parent component that renders both siblings. The parent then passes the state value to one child and the setter callback to the other.

// PROBLEM: SearchInput holds state that ResultsList needs
// but siblings can't communicate directly

function SearchInput() {
  const [query, setQuery] = useState(''); // stuck here
  return <TextInput value={query} onChangeText={setQuery} />;
}

function ResultsList() {
  // How do we access 'query' from the sibling? We can't!
  return <FlatList data={/* needs query */} />;
}

Lifting State to the Common Ancestor

Move the shared state to the closest common ancestor — the component that renders both siblings. The parent now owns the state and passes it down as props: the search query goes to the results list, and the setter function goes to the search input. The siblings communicate through the parent: the search input calls the setter (passed as a prop), which updates the parent's state, which flows the new query value to the results list as a new prop. This is the fundamental React data flow pattern.

import { useState } from 'react';
import { View, TextInput, Text } from 'react-native';

// Parent owns the shared state
export default function SearchScreen() {
  const [query, setQuery] = useState('');
  const results = ITEMS.filter(item =>
    item.toLowerCase().includes(query.toLowerCase())
  );

  return (
    <View style={{ flex: 1, padding: 16 }}>
      <SearchInput query={query} onQueryChange={setQuery} />
      <ResultsList results={results} />
    </View>
  );
}

const ITEMS = ['Apple', 'Banana', 'Blueberry', 'Cherry', 'Avocado'];

Writing the Child Components

With lifted state, the child components become simple and focused. The SearchInput component receives query (current value) and onQueryChange (to update it) as props. The ResultsList receives the filtered results array. Neither child manages state — they are controlled components whose behavior is entirely driven by their props. This makes both components easy to test in isolation: just pass the props and assert the rendered output.

import { TextInput, FlatList, Text, View, StyleSheet } from 'react-native';

// Controlled: receives value and updater as props
function SearchInput({ query, onQueryChange }) {
  return (
    <TextInput
      value={query}
      onChangeText={onQueryChange}
      placeholder='Search...'
      style={styles.input}
    />
  );
}

// Pure display: receives filtered data as prop
function ResultsList({ results }) {
  return (
    <FlatList
      data={results}
      keyExtractor={item => item}
      renderItem={({ item }) => (
        <Text style={styles.item}>{item}</Text>
      )}
    />
  );
}

const styles = StyleSheet.create({
  input: { borderWidth: 1, borderColor: '#ccc', borderRadius: 8, padding: 12, marginBottom: 12 },
  item: { padding: 12, borderBottomWidth: 1, borderBottomColor: '#eee' },
});

Finding the Nearest Common Ancestor

The key question when lifting state is: 'Which is the lowest component in the tree that renders all the components needing this state?' Lift state to exactly that component — no higher. Lifting too high (e.g., all the way to App) causes unnecessary re-renders of unrelated components. The nearest common ancestor is the right balance between accessibility (all consumers can receive the state as props) and performance (only the subtree that needs the state re-renders). Draw your component tree and trace upward from each consumer to find where paths converge.

// Component tree:
// App
// └── TabBar (selected tab)
//     ├── HomeTab
//     │   └── Feed
//     └── ProfileTab
//
// If 'selected tab' is needed by TabBar AND by Feed to filter content,
// lift it to TabBar (nearest common ancestor of both).
// DO NOT lift all the way to App unnecessarily.

function TabBar() {
  const [activeTab, setActiveTab] = useState('home');
  return (
    <View>
      <TabButtons activeTab={activeTab} onChange={setActiveTab} />
      {activeTab === 'home' ? <HomeTab /> : <ProfileTab />}
    </View>
  );
}

Multiple Siblings Sharing State

When three or more siblings need the same state, lift it once to their shared parent and pass it to each sibling that needs it. For example, a product detail screen might have an ImageGallery, a VariantPicker, and an AddToCartButton. The selected variant state lives in the parent screen component and flows to all three. VariantPicker gets the setter to change the selection. ImageGallery shows images for the selected variant. AddToCartButton adds the specific selected variant to the cart.

import { useState } from 'react';
import { View } from 'react-native';

const VARIANTS = ['Red / S', 'Red / M', 'Blue / S', 'Blue / M'];

export default function ProductDetailScreen() {
  const [selectedVariant, setSelectedVariant] = useState(VARIANTS[0]);

  return (
    <View style={{ flex: 1 }}>
      <ImageGallery variant={selectedVariant} />
      <VariantPicker
        variants={VARIANTS}
        selected={selectedVariant}
        onSelect={setSelectedVariant}
      />
      <AddToCartButton variant={selectedVariant} />
    </View>
  );
}

Callback Props vs. Shared State

Sometimes components share an action rather than a state value. A common example: a list screen with a cart icon in the header — pressing 'Add to Cart' on any list item should update the badge count in the header. Both the list items and the header are siblings under the same parent screen. The parent holds the cart count in state, passes the count to the header via props, and passes an onAddToCart callback to the list. Items call the callback; the parent updates its state; the header badge re-renders with the new count.

import { useState } from 'react';
import { View } from 'react-native';

export default function ShopScreen() {
  const [cartCount, setCartCount] = useState(0);

  function addToCart(item) {
    // Business logic lives in the parent
    setCartCount(prev => prev + 1);
    console.log('Added:', item.name);
  }

  return (
    <View style={{ flex: 1 }}>
      {/* Sibling 1: displays count from parent state */}
      <ShopHeader cartCount={cartCount} />
      {/* Sibling 2: triggers parent state update */}
      <ProductList onAddToCart={addToCart} />
    </View>
  );
}

When Lifting State Becomes Prop Drilling

If the common ancestor is many levels above the components that need the state, you end up with prop drilling — passing props through many intermediate components that don't use them. For example, if the common ancestor is the App root and there are 5 component levels between App and the consumers, every intermediate component becomes a messenger. The solution for deep sharing is Context API (for data that many components need) or a state management library like Zustand or Redux. The rule of thumb: lift state, but if it crosses more than 2–3 levels without being used in between, consider Context instead.

// When prop drilling gets too deep, switch to Context
// Instead of:
function App() {
  const [user, setUser] = useState(null);
  return <Nav user={user}>   // not used
    <Drawer user={user}>     // not used
      <Screen user={user}>  // not used
        <ProfileCard user={user} />  // finally used
      </Screen>
    </Drawer>
  </Nav>;
}

// Use Context:
const UserContext = React.createContext(null);
function App() {
  const [user, setUser] = useState(null);
  return (
    <UserContext.Provider value={user}>
      <Nav><Drawer><Screen><ProfileCard /></Screen></Drawer></Nav>
    </UserContext.Provider>
  );
}

Practical Example: Temperature Converter

A classic demonstration of lifting state: two temperature input fields (Celsius and Fahrenheit) that stay in sync. Each input field takes the current temperature and an onChange callback. The parent holds the temperature in one unit (say Celsius) and converts it for the other input. When either input changes, the parent converts and updates its state. Both inputs receive the correct value from parent state, keeping them perfectly synchronized through the shared parent state.

import { useState } from 'react';
import { View, Text, TextInput, StyleSheet } from 'react-native';

function TempInput({ label, value, onChangeText }) {
  return (
    <View style={styles.row}>
      <Text style={styles.label}>{label}</Text>
      <TextInput
        value={value}
        onChangeText={onChangeText}
        keyboardType='decimal-pad'
        style={styles.input}
      />
    </View>
  );
}

export default function TemperatureConverter() {
  const [celsius, setCelsius] = useState('');

  const fahrenheit = celsius !== '' ? (parseFloat(celsius) * 9/5 + 32).toFixed(1) : '';

  function handleFahrenheitChange(f) {
    const c = f !== '' ? ((parseFloat(f) - 32) * 5/9).toFixed(1) : '';
    setCelsius(c);
  }

  return (
    <View style={{ padding: 24 }}>
      <TempInput label='Celsius' value={celsius} onChangeText={setCelsius} />
      <TempInput label='Fahrenheit' value={fahrenheit} onChangeText={handleFahrenheitChange} />
    </View>
  );
}

const styles = StyleSheet.create({
  row: { flexDirection: 'row', alignItems: 'center', marginBottom: 12 },
  label: { width: 100, fontSize: 16 },
  input: { flex: 1, borderWidth: 1, borderColor: '#ccc', borderRadius: 8, padding: 10 },
});

Collocate State Close to Where It's Used

The mirror principle to lifting state is keeping state as low as possible. If only one component needs a piece of state, keep it inside that component — don't lift it unnecessarily. For example, a dropdown's open/closed state doesn't need to be in the parent screen unless the parent needs to react to it. Keeping local state local improves performance (fewer components re-render) and makes code easier to reason about (state and the UI that uses it are in the same place). Only lift when two or more components truly need the same data.

// Local state: Accordion open/close is private to Accordion
function Accordion({ title, children }) {
  const [open, setOpen] = useState(false); // stays local — parent doesn't care
  return (
    <View>
      <TouchableOpacity onPress={() => setOpen(prev => !prev)}>
        <Text>{title} {open ? '▲' : '▼'}</Text>
      </TouchableOpacity>
      {open && <View style={{ paddingLeft: 16 }}>{children}</View>}
    </View>
  );
}

// Only lift open state to parent IF the parent needs to:
// - Know which accordion is open to close others
// - Save/restore the open state on navigation
// Otherwise, keep it local!

Uncontrolled vs. Controlled Components

A component is controlled when its state is driven entirely by props (and changed via callbacks) — like the search input example. It is uncontrolled when it manages its own internal state without exposing it to the parent. Most of the time in React, you use controlled components because they are predictable and easy to test. Uncontrolled inputs (using ref to read values) are used occasionally for performance (avoiding re-renders on every keystroke) or for integrating with non-React code. The default form elements in React Native's TextInput are controlled when you pass value and onChangeText.

import { TextInput, useRef } from 'react-native';

// Uncontrolled: parent reads value on demand via ref
function UncontrolledInput({ inputRef }) {
  return (
    <TextInput
      ref={inputRef}
      // No value prop: TextInput manages its own text
      defaultValue='Initial text'
    />
  );
}

// Parent reads the value when the form is submitted:
function Form() {
  const inputRef = useRef(null);
  function handleSubmit() {
    // Use _lastNativeText (not recommended) or store value in ref.current
    console.log('Value:', inputRef.current?.props?.value);
  }
}

Real-World: Filter and Results Panel

A practical application of lifted state: a search screen with a filter bar (category selector, price range slider, sort picker) above a results list. Each filter value lives in the parent SearchScreen component. The filter bar receives current filter values and setter callbacks as props. The results list receives the current filters and re-renders whenever any filter changes. The parent also fetches new results whenever filters change (via useEffect on filter dependencies). This coordination through a single parent makes the search feature predictable and easy to test.

import { useState, useEffect } from 'react';
import { View } from 'react-native';

export default function SearchScreen() {
  // All filter state lifted here
  const [query, setQuery] = useState('');
  const [category, setCategory] = useState('all');
  const [sortBy, setSortBy] = useState('relevance');
  const [results, setResults] = useState([]);

  // Fetch results whenever any filter changes
  useEffect(() => {
    fetchResults({ query, category, sortBy }).then(setResults);
  }, [query, category, sortBy]);

  return (
    <View style={{ flex: 1 }}>
      <FilterBar
        query={query} onQueryChange={setQuery}
        category={category} onCategoryChange={setCategory}
        sortBy={sortBy} onSortChange={setSortBy}
      />
      <ResultsList results={results} />
    </View>
  );
}

Quick Check

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

Lesson Recap

In this lesson you learned: lifting state to the nearest common ancestor allows siblings to share data through their parent, controlled components receive their value and updater as props making them predictable and testable, and state should stay as low as possible — only lift it when multiple components truly need it. Next up we build an interactive counter app combining all of these concepts.

常见问题解答

「提升状态」课时是免费的吗?

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

「提升状态」这节课中我会学到什么?

将共享状态移至最近的公共祖先组件,并将值和更新回调作为 props 传给兄弟组件,使它们保持同步。 你通过在浏览器中直接运行的动手代码来练习 React Native Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

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

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

「提升状态」课时需要多长时间?

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

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

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

此课程中的所有课时

  1. 使用 props 传递数据
  2. 使用 useState 管理组件状态
  3. 提升状态
  4. 构建交互式计数器应用
← 返回 React Native Academy