我有一个根组件(App),它呈现了嵌套的导航,如代码所示。 在应用程序内部,我拥有所有子对象都使用的用户对象(状态存储)。它包含有关您所在的组的信息。
final class DataStore: ObservableObject {
@Published var bools: [Bool] = [true, false]
}
extension Binding where Value: MutableCollection, Value.Index == Int {
func element(_ idx: Int) -> Binding<Value.Element> {
return Binding<Value.Element>(
get: {
return self.wrappedValue[idx]
}, set: { (value: Value.Element) -> () in
self.wrappedValue[idx] = value
})
}
}
struct ContentView: View {
@EnvironmentObject var dataStore: DataStore
var body: some View {
HStack {
Spacer()
Toggle(isOn: $dataStore.bools.element(0)) {
Text(dataStore.bools[0] ? "On" : "Off")
}
Spacer()
Toggle(isOn: $dataStore.bools.element(1)) {
Text(dataStore.bools[1] ? "On" : "Off")
}
Spacer()
}
}
}
现在,当我想设置更新的用户(通过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设置)时,导航不会保留其路线,而是返回到StartPage。
但是,我要改为使用新用户重新渲染GroupDetail。
如何保持导航状态?还是您认为我有设计缺陷,并且有解决此问题的想法?谢谢!
(是的,我只想将用户对象保留在App内并向下传递。主要原因是只有很少的API调用)
答案 0 :(得分:1)
您不应在身份验证上创建新的导航器,而应将一条路由添加到导航器,这将是您的默认路由,并且该路由将负责您的登录。
应该传递一个回调以设置用户,如下所示:
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');
}
希望这会有所帮助。
答案 1 :(得分:0)
根据文档,您必须保留用户导航状态。
了解更多here。