โครงการของฉันกำลังวนซ้ำผ่านอาร์เรย์ข้อมูลในองค์ประกอบย่อย Main
และฉันกำลังพยายามอัปเดตสถานะในองค์ประกอบหลัก App
ในเหตุการณ์ (ปัดไปทางขวาบนการ์ดใน Main
) เพื่อให้ฉันสามารถเข้าถึงข้อมูลที่ ถูก 'ปัดไปทางขวา' บนส่วนประกอบพี่น้องใน Favorites
หวังว่ามันจะสมเหตุสมผลนะ?
โครงสร้างโครงการเป็นดังนี้:
App
|__ Rootstack
|
|__Favorites
|__Main
ในองค์ประกอบ Main
ของฉัน ฉันกำลังแมปอาร์เรย์ collection
และวนซ้ำผ่าน:
collection = imagedata;
// a local JSON array of data that I am looping thru in Main
class Main extends React.Component {
_toFavs = () => {
this.props.navigation.navigate('Favorites');
};
render() {
const contents = collection.map((item, index) => {
return (
<Card key={index}>
......
</Card>
)
});
return (
<View>
<CardStack
onSwiped={() => {console.log('onSwiped')}
onSwipedRight={() => console.log('onSwipedLeft')}>
//
//HERE IS THE PART - HOW TO UPDATE THE 'favoritesList' array in the parent 'App's state?
//
{contents}
</CardStack>
</View>
);
}
}
const RootStack = StackNavigator(
{
Main: {
screen: Main},
Favorites: {
screen: Favorites}
},
{
initialRouteName: 'Main'
}
);
class Favorites extends React.Component {
// The plan is to eventually access the favoritesList array in App's state here and display cards that were swiped right in the Main component.
_onPress = () => {
this.props.navigation.navigate('Main');
};
render() {
return (
<View><Text>Hello!</Text></View>
);
}
}
export default class App extends Component<{}> {
constructor(props) {
super(props);
this.state = {
favoritesList: []
};
}
render() {
return <RootStack />;
}
}
ฉันพบคำตอบอื่น ๆ ในการอัปเดตสถานะเช่น this.setState({ favoritesList: [...this.state.favoritesList, 'new value'] })
แต่ฉันจะทำสิ่งนี้กับ .state เป็น App
ในขณะที่ฉันอยู่ในองค์ประกอบลูก Main
ได้อย่างไร
ขอบคุณล่วงหน้า!