为什么选择器在调度后没有刷新到回调函数?


const signedIn = useSelector(signedInState);
const handleSignInSubmit = useCallback(async() => {
await dispatch(signInUser(username.value, password.value))
console.log(signedIn)//always false, never became true
if(signedIn)
history.push("/")
}

}

}, [dispatch,username.value,password.value,signedIn]);

所以我有这样的代码,最初signedIn选择器是false,但当我调用分派时,它变成了true,但如果我尝试在分派后将其console.log记录到回调中,他永远不会更改状态值(但在存储中,值会更改(为什么会发生这种情况?

//action 
export const signInUser = (username, password) => async(dispatch) =>{

const {
SIGN_IN_USER_SUCCESS,
//SIGN_IN_USER_FAIL,
} = AuthKeys;
var returning;
var authenticationData = {
Username: username,
Password: password,
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var poolData = {
UserPoolId: settings.UserPoolId,
ClientId: settings.ClientId,
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username: username,
Pool: userPool,
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: async function (result) {
console.log("access token + " + result.getAccessToken().getJwtToken());
await dispatch({
type: SIGN_IN_USER_SUCCESS,
payload: cognitoUser,
});
},
onFailure: function (err) {
alert(err.message);

},
});
};
//reducer 
const initialState={
signedIn        : false,
signedInUser    : null,
}
export default (state = initialState, action) => {
const {
//Requests
SIGN_IN_USER_SUCCESS,
//SIGN_IN_USER_FAIL,
} = AuthKeys;
switch(action.type){
case SIGN_IN_USER_SUCCESS:
return { ...state,
signInEmailData     : initialState.signInEmailData,
signInPasswordData  : initialState.signInPasswordData,
signedIn            : true,
signedInUser        : action.payload}
case SIGN_OUT_USER_SUCCESS:
return{
...state,
signedIn        : false,
signedInUser    : INITIAL_STATE.signedInUser, 
}
}
return state;
}
//selector
export const  signedInUserState=(state)=>state.Auth.signedInUser

这是代码的其余部分,其中包含一些关于减少程序和操作的信息

useSelector期望传递一个函数,在该函数中,您可以从存储中选择所需的确切值,如下所示:const counter = useSelector(state => state.counter)。我不确定signedInState在这种情况下到底是什么,您应该提供更多的代码。

最新更新