reduxによってディスパッチされるアクションのロジックとreactのコンポーネントを分離するためのactionCreatorsがあります。/actions/authenticate.js
Here is my authenticate.js
which is my 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
次に、それを mysomeComponent.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 アクションをディスパッチし、promise を返します。解決されたかどうかにかかわらず、正しい画面にリダイレクトまたはナビゲートできます。
誰かが助けてくれれば感謝します。前もって感謝します。