【发布时间】:2019-04-09 21:34:43
【问题描述】:
我正在我的 React Native 应用程序中设置身份验证流程,我几乎可以让一切正常工作,除了我无法确定使用this.props.navigation.navigate("Main"); 导航到登录堆栈的实际正确位置。
我的应用顶部有一个 Switch Navigator,它呈现身份验证堆栈(它自己的开关导航)和主堆栈:
// App.js
const AppContainer = createAppContainer(
createSwitchNavigator({
Auth: AuthNavigator,
Main: MainTabNavigator,
})
);
export default class App extends Component {
render() {
return (
<Provider store={store}>
<View style={styles.container}>
<AppContainer />
</View>
</Provider>
);
}
}
登录屏幕现在是一个完整的虚拟设置(它调用本地 api 并且无论如何都会成功)。 注意渲染方法开头的条件:
// LoginView.js
class LoginView extends Component {
state = { username: "", password: "" };
handleLogin() {
this.props.login.call(this);
}
render() {
if (this.props.user) {
this.props.navigation.navigate("Main");
return null;
}
return (
<View style={styles.container}>
<Overlay>
<View style={styles.modalContainer}>
<DotIndicator color={"darkgrey"} />
<Text>Logging in...</Text>
</View>
</Overlay>
// ... input components ...
<Button
title="Login"
onPress={this.handleLogin.bind(this)}
/>
</View>
);
}
}
export default connect(
state => ({
isLoading: state.auth.isLoading,
user: state.auth.user,
error: state.auth.error
}),
{ login }
)(LoginView);
现在,这在技术上有效,但我收到错误 Warning: Cannot update during an existing state transition (such as withinrender). Render methods should be a pure function of props and state.。
我理解这是因为我在 render 中调用了 navigate。有道理。
我已尝试从我的登录操作中导航:
export function login() {
return dispatch => {
dispatch({ type: "LOGIN_START" });
fetch(url) // this will need to be a POST session (not a GET user)
.then(res => res.json())
.then(users => {
dispatch({ type: "LOGIN_SUCCESS", payload: users[0] });
console.log("Login succeeded");
this.props.navigation.navigate("Main");
})
.catch(error => {
console.warn("login failed");
dispatch({ type: "LOGIN_FAILURE", payload: error });
});
};
}
它可以工作,但在关注点分离方面当然是非常错误的,当我尝试使用它来处理登录失败时,这种解决方案也没有真正延伸。
我也考虑过在我的handleLogin() 函数(由我的登录按钮调用)中执行此操作,有无异步/等待:
async handleLogin() {
await this.props.login.call(this);
console.log("Navigating to main screen");
this.props.navigation.navigate("Main");
}
但是导航发生在操作完成和用户登录之前,一旦授权流程是真实的,这当然是不可接受的。 (另外,当我使用 async/await 执行此操作时,“登录成功”会被记录两次!击败我)。在我的handleLogin() 函数中,我确实感觉我走在了正确的轨道上。
我的navigate 电话应该放在哪里?
【问题讨论】:
标签: react-native redux