Мой проект перебирает массив данных в дочернем компоненте 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
?
Заранее спасибо!