React Native异步场景传参:点击按钮存储gameId至AsyncStorage
Got it, let's work through this together. You want to add a button to each session card that saves the corresponding session.gameId to AsyncStorage and triggers your onSubmit function when clicked. Here's a clean, practical implementation:
First, set up AsyncStorage
If you're using React Native 0.60+, you'll need the official AsyncStorage package (the core one is deprecated). Install it first:
npm install @react-native-async-storage/async-storage # or yarn add @react-native-async-storage/async-storage
Then import it at the top of your component file:
import AsyncStorage from '@react-native-async-storage/async-storage';
Add the button and submit handler
Since you're using a class component (judging by this.state), add an async handler method to handle the button click. This method will first save the gameId to storage, then call your onSubmit function:
class YourComponent extends React.Component { // Async handler to save gameId and trigger submission async handleSessionSubmit(gameId) { try { // Save the gameId to AsyncStorage with a descriptive key await AsyncStorage.setItem('@current_game_id', gameId); // Call your existing onSubmit function this.onSubmit(); // If you need to pass the gameId to onSubmit too, use: // this.onSubmit(gameId); } catch (error) { // Always handle storage errors to avoid silent failures console.error('Failed to save gameId to AsyncStorage:', error); } } render() { return ( <View> {this.state.sessions.map((session, index) => { // Always add a unique key to mapped elements (use session.id if available instead of index) return ( <View key={index} style={styles.cardContainer}> <Text style={styles.title}>{session.title}</Text> <Text style={styles.text}>Organisator: {session.organizer}</Text> {/* Add your other session fields here */} {/* Submit button tied to this specific session */} <Button title="Submit This Session" onPress={() => this.handleSessionSubmit(session.gameId)} style={styles.submitButton} /> </View> ); })} </View> ); } }
Quick notes for best practices:
- Key prop: Use a unique identifier from your session object (like
session.id) instead ofindexif possible—it's better for React's re-rendering performance. - Error handling: The
try/catchblock ensures you'll catch any issues with AsyncStorage (like storage limits or permission problems) instead of having your app crash silently. - Function component alternative: If you were using a function component, you'd use
useCallbackto optimize the handler:
import { useCallback } from 'react'; const YourFunctionComponent = ({ onSubmit, sessions }) => { const handleSessionSubmit = useCallback(async (gameId) => { try { await AsyncStorage.setItem('@current_game_id', gameId); onSubmit(gameId); // Pass gameId if needed } catch (error) { console.error('Storage error:', error); } }, [onSubmit]); return ( <View> {sessions.map((session) => ( <View key={session.id} style={styles.cardContainer}> <Text style={styles.title}>{session.title}</Text> <Text style={styles.text}>Organisator: {session.organizer}</Text> <Button title="Submit" onPress={() => handleSessionSubmit(session.gameId)} /> </View> ))} </View> ); };
内容的提问来源于stack exchange,提问作者Brian Neyens
相关产品推荐
相关产品推荐

