![](/img/trans.png)
[英]The navigation prop is missing for this navigator. In react-navigation v3 and v4 you must set up your app container directly
[英]setState() on root container doesn't keep routes of react-navigation (V3)
我有一個根組件(App),它呈現代碼中所示的嵌套導航。 在應用程序內部,我擁有所有子對象都使用的用戶對象(狀態存儲)。 它包含有關您所在的組的信息。
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
user: null
}
}
render() {
if (!this.state.user) {
// from the login component, I make an API call to my backend.
// If the user logs in, I do app.setState({user: loggedInUser}) from inside the LoginComponent
return <LoginComponent app={this} />
}
return createAppContainer(createSwitchNavigator({
MainApp: {
screen: createBottomTabNavigator({
StartPage: {
screen: ({ navigation }) => {
return <StartPage navigation={navigation} app={this} />
}
},
Groups: {
screen: createStackNavigator({
ListGroups: {
// When clicking on a Group from the GroupsPage, I execute:
// this.props.navigation.navigate('GroupDetail', { group, app })
// (from inside the GrousPage screen)
screen: ({ navigation }) => <GroupsPage navigation={navigation} app={this} />
},
GroupDetail: {
// Inside the GroupDetail, you can leave or join a group.
// If you do that, I'm making an API call and get the new user object.
// Then, I do this.props.navigation.getParam('app').setState({user: newUser})
// "app" was passed from ListGroups
screen: GroupDetail
}
})
}
})
}
}))
}
}
現在,當我想設置更新的用戶(通過GroupDetail通過app.setState({user: newUser})
)時,導航不會保留其路線,而是返回到StartPage。 但是,我想要的是用新用戶重新渲染GroupDetail。
我將如何保持導航狀態? 還是您認為我有設計缺陷,並且有解決此問題的想法? 謝謝!
(是的,我只想將用戶對象保留在App內並向下傳遞。主要原因是只有很少的API調用)
您不應在身份驗證上創建新的導航器,而應將一條路由添加到導航器,這將是您的默認路由,並且該路由將負責您的登錄。
應該將其傳遞給回調以設置用戶,如下所示:
setUser = user => this.setState({user});
return <AuthPage setUser={this.setUser} /> // You also don't have to pass navigation. It will be passed automatically.
在您的AuthPage中,您可以設置用戶
this.props.setUser(newUser);
並使用導航道具導航到所需的路線,或者返回上一條路線:
this.props.navigation.navigate('App');
Or this.props.navigation.goBack();
要使用戶保持登錄狀態,您應該檢查用戶是否已登錄Auth路由並做出相應的反應:
componentDidMount() {
const user = getUser(); // This depends on how you persist the user
this.props.navigation.navigate(user ? 'App' : 'Auth');
}
希望這可以幫助。
根據文檔,您必須保留用戶導航狀態。
在這里閱讀更多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.