我有一个actionCreators来分离redux调度的动作/actions/authenticate.js
的逻辑和react的组件。
这是我的authenticate.js
,这是我的actionCreators
export function login(email, password) { // Fake authentication function
return async dispatch => {
dispatch(loginRequest()); // dispatch a login request to update the state
try {
if (email.trim() === "test123@nomail.com" && password === "123456") { //If the email and password matches
const session = { token: "abc1234", email: email, username: "test123" } // Create a fake token for authentication
await AsyncStorage.setItem(DATA_SESSION, JSON.stringify(session)) // Stringinfy the session data and store it
setTimeout(() => { // Add a delay for faking a asynchronous request
dispatch(loginSuccess(session)) // Dispatch a successful sign in after 1.5 seconds
return Promise.resolve()
}, 1500)
} else { // Otherwise display an error to the user
setTimeout(() => { // Dispatch an error state
dispatch(loginFailed("Incorrect email or password"))
}, 1500)
}
} catch (err) { // When something goes wrong
console.log(err)
dispatch(loginFailed("Something went wrong"));
return Promise.reject()
}
};
} // login
然后我在我someComponent.js
的导入那个actionCreator并使用bindActionCreators绑定它。
下面是这样的:
import { bindActionCreators } from "redux";
import * as authActions from "../actions/authenticate";
import { connect } from "react-redux";
然后我将该动作连接到我的组件,即Login.js
export default connect(
state => ({ state: state.authenticate }),
dispatch => ({
actions: bindActionCreators(authActions, dispatch)
})
)(Login);
所以我可以直接在 actionCreator 中调用该函数Login.js
下面是这样的:
onPress={() => {
this.props.actions.login(this.state.email, this.state.password)
}}
但是我想要发生的是这个函数将调度一个redux 操作并在可能的情况下返回一个Promise?
像这样的东西:
onPress={() => {
this.props.actions.login(this.state.email, this.state.password)
.then(() => this.props.navigation.navigate('AuthScreen'))
}}
我想要发生的是当我尝试登录时。调度那些异步 redux thunk 操作并返回一个承诺。如果已解决,我可以重定向或导航到正确的屏幕。
感谢有人可以提供帮助。提前致谢。