I'm trying to navigate to another screen when I click on one of the items on the flat list.
The code that I have here worked for a couple of days but now it doesn't, straight away when the app loads, the EventDetailScreen is opened even before I click on any of the flat list items, then when I press the back button from the EventDetailScreen which brings me back to the EventListScreen, if I click on any of the list items nothing happens and I don't get brought to the EventDetailScreen.
I also get an error:
Warning: Cannot update during an existing state transition (such as within
render
or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved tocomponentWillMount
.
I am new to React Native so any help would be much appreciated!
I am using:
"react-navigation": "^2.7.0",
"react": "16.4.1",
"react-native": "0.56.0",
I used this answer Navigating to each item in FlatList on SO to get it working initially.
EventListScreen.js
export default class EventListScreen extends Component {
constructor() {
super();
this.ref = firebase.firestore();
this.unsubsribe = null;
this.state = {
eventName: '',
eventLocation: '',
loading: true,
events: [],
};
}
componentDidMount() {
console.log('EventsListScreen1');
this.unsubsribe = this.ref.onSnapshot(this.onCollectionUpdate)
}
componentWillUnmount() {
this.unsubsribe();
}
openDetails = () => {
this.props.navigation.navigate('EventDetailScreen');
};
render() {
if (this.state.loading) {
return null;
}
return (
<Container>
<FlatList
data={this.state.events}
// Get the item data by referencing as a new function to it
renderItem={({item}) =>
<Event
openDetails={() => this.openDetails()}
{...item} />}
/>
<View style={{flex: 1}}>
<Fab
active={this.state.active}
direction="left"
containerStyle={{}}
style={{backgroundColor: '#5067FF'}}
position="bottomRight"
onPress={() =>
this.props.navigation.navigate('EventForm')
}>
<Icon
name="ios-add"/>
</Fab>
</View>
</Container>
);
}
Event.js
export default class Event extends Component {
render() {
return (
<Card>
<CardSection>
<Text>{this.props.eventName}</Text>
</CardSection>
<TouchableOpacity
onPress={this.props.openDetails()}
>
<CardSection>
<Image
style={{
width: 350,
height: 300
}}
source={{
uri: this.props.imageDownloadUrl
}}
/>
</CardSection>
<CardSection>
<Text>{this.props.eventLocation}</Text>
</CardSection>
</TouchableOpacity>
</Card>
);
}};
EventDetailScreen.js
export default class EventDetailScreen extends Component {
render() {
/* 2. Get the param, provide a fallback value if not available */
const { navigation } = this.props;
const itemId = navigation.getParam('itemId', 'NO-ID');
return (
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}}>
<Text>Details Screen</Text>
</View>
);
}}