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

React Native:StackNavigator子组件中如何追加父组件状态数组?

How to Update Parent State from Child Component for Shared Favorites Data

Hey there! Let's walk through exactly how to make this work. The key concept here is lifting state up—since both your Main (where swiping happens) and Favorites (where you display saved cards) need access to the same favorites data, we'll keep that state in their common parent component (App), then pass down the tools to update and access that state via props.

Step 1: Set Up State in the Parent App Component

First, we'll initialize the favorites state in App and create a function to add items to this state. This function will be passed down to Main so it can trigger updates when a card is swiped right.

import { useState } from 'react';
import Main from './Main';
import Favorites from './Favorites';

function App() {
  // Initialize empty array for favorites
  const [favorites, setFavorites] = useState([]);

  // Function to add a card to favorites (prevents duplicates optionally)
  const addToFavorites = (cardData) => {
    // Optional: Check if the card is already in favorites to avoid duplicates
    const isAlreadyFavorite = favorites.some(item => item.id === cardData.id);
    if (!isAlreadyFavorite) {
      // Use the previous state to ensure we're updating correctly
      setFavorites(prevFavorites => [...prevFavorites, cardData]);
    }
  };

  return (
    <div className="app-wrapper">
      {/* Pass your collection data and the add function to Main */}
      <Main collection={yourCollectionArray} addToFavorites={addToFavorites} />
      {/* Pass the favorites array to the Favorites component */}
      <Favorites favorites={favorites} />
    </div>
  );
}

export default App;

Step 2: Handle Swipe Events in the Main Component

In Main, we'll receive the collection data and addToFavorites function as props. When a card is swiped right, we'll call this function with the card's data to update the parent state.

function Main({ collection, addToFavorites }) {
  // Handler for right swipe event
  const handleRightSwipe = (cardData) => {
    // Trigger the parent's add function with the swiped card's data
    addToFavorites(cardData);
    // Add any other post-swipe logic here (e.g., remove the card from the current list)
  };

  return (
    <div className="main-container">
      {collection.map(card => (
        <div
          key={card.id}
          className="card"
          // Replace with your actual swipe event handler (depends on your swipe library/custom implementation)
          onSwipeRight={() => handleRightSwipe(card)}
        >
          {/* Render your card content here */}
          <h3>{card.title}</h3>
          <p>{card.description}</p>
        </div>
      ))}
    </div>
  );
}

export default Main;

Note: If you're using a specific swipe library (like react-swipeable or similar), the event name might differ—just make sure to call handleRightSwipe(card) when the right swipe is detected.

Step 3: Display Favorites in the Favorites Component

Finally, the Favorites component will receive the favorites array as a prop and render the saved cards.

function Favorites({ favorites }) {
  return (
    <div className="favorites-container">
      <h2>My Favorite Cards</h2>
      {favorites.length === 0 ? (
        <p>Swipe right on some cards to add them here!</p>
      ) : (
        favorites.map(favorite => (
          <div key={favorite.id} className="favorite-card">
            <h3>{favorite.title}</h3>
            <p>{favorite.description}</p>
          </div>
        ))
      )}
    </div>
  );
}

export default Favorites;

For Class Components (If You're Using Them)

If you're working with class components instead of functional components, the logic is identical—just the syntax changes:

App Component (Class Version)

import React, { Component } from 'react';
import Main from './Main';
import Favorites from './Favorites';

class App extends Component {
  state = {
    favorites: []
  };

  addToFavorites = (cardData) => {
    const isAlreadyFavorite = this.state.favorites.some(item => item.id === cardData.id);
    if (!isAlreadyFavorite) {
      this.setState(prevState => ({
        favorites: [...prevState.favorites, cardData]
      }));
    }
  };

  render() {
    return (
      <div className="app-wrapper">
        <Main collection={yourCollectionArray} addToFavorites={this.addToFavorites} />
        <Favorites favorites={this.state.favorites} />
      </div>
    );
  }
}

export default App;

Main Component (Class Version)

import React, { Component } from 'react';

class Main extends Component {
  handleRightSwipe = (cardData) => {
    this.props.addToFavorites(cardData);
  };

  render() {
    const { collection } = this.props;
    return (
      <div className="main-container">
        {collection.map(card => (
          <div
            key={card.id}
            className="card"
            onSwipeRight={() => this.handleRightSwipe(card)}
          >
            <h3>{card.title}</h3>
            <p>{card.description}</p>
          </div>
        ))}
      </div>
    );
  }
}

export default Main;

This approach ensures that your state stays in sync across all components that need it—when a card is swiped right in Main, App's state updates, and Favorites automatically re-renders with the new data.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:39:46