[英]Navigate to another screen from Flat list item
單擊平面列表中的一個項目時,我試圖導航到另一個屏幕。
我在這里工作的代碼已經使用了幾天,但是現在沒有了,當應用程序加載時,即使在我單擊任何平面列表項目之前,EventDetailScreen也已打開,然后當我按EventDetailScreen,這使我回到EventListScreen,如果我單擊任何列表項,則什么也不會發生,也不會進入EventDetailScreen。
我也得到一個錯誤:
警告:在現有狀態轉換期間(例如在
render
或其他組件的構造函數中)無法更新。 渲染方法應該純粹是道具和狀態的函數; 構造函數的副作用是反模式,但是可以將其移至componentWillMount
。
我是React Native的新手,所以我們將不勝感激!
我正在使用: "react-navigation": "^2.7.0",
"react": "16.4.1", "react-native": "0.56.0",
我使用此答案導航至 SO上FlatList的每個項目,以使其最初開始工作。
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>
);
}}
這可能是因為Event
組件中的以下行。
<TouchableOpacity
onPress={this.props.openDetails()} // <-- this line to be specific
> ... </>
EventScreenList
呈現列表后,第一行將執行openDetails()
方法,該方法將切換屏幕。
您可以使用onPress={() => this.props.openDetails()}
來避免這種情況。
在EventScreenList組件的構造函數或componentDidMount中具有以下內容也是一個好主意,因為這兩個函數都使用this
語句的上下文。
this.openDetails = this.openDetails.bind(this);
this.onCollectionUpdate = this.onCollectionUpdate.bind(this);
要檢查上述陳述的重要性,請嘗試
<TouchableOpacity
onPress={this.props.openDetails} // <-- this line
> ... </>
該警告消息是由於狀態更新完成之前的導航而引起的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.