我正在将redux(redux版本-4.0.x,react-redux版本-7.1.x)集成到具有react-navigation(version-4.0.x)的现有react-native(version-0.60.5)应用程序中并修改来自Axios的现有后端Http请求,以使用redux-thunk中间件(版本-2.3.x)在redux操作创建者中获取API。
在获取呼叫的成功功能中,我无法弄清楚如何设置反应导航以重定向到另一个屏幕。
在这里,我不打算使用react-navigation/redux-helpers将导航切换到redux,但是需要保持反应导航来管理应用程序的导航
在Redux action Creator(登录)中获取调用示例:
const fetchLogin = (username,password) => {
const url = hostUrl + '/oauth/token';
return(dispatch) => {
dispatch(getLoginAttempt(true))
return(fetch(url,{
method: 'POST',headers: {
'accept': 'application/json','Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',},body:"client_secret&username="+username+"&password="+password
}))
.then((response) => {
console.log("Response",response);
if(response.status >= 200 && response.status < 300) {
dispatch(getLoginAttempt(false))
response.json()
.then((responseJson) => {
console.log("responseJSON",responseJson);
dispatch(getLoginAttemptSuccess(responseJson))
try{
setaccessToken(responseJson.access_token);
setaccessToken5(responseJson.access_token);
} catch (e) {
console.log("Error Saving the access Token");
}
})
} else {
response.json()
.then((responseJson) => {
console.log("responseJSON",responseJson);
dispatch(getLoginAttempt(false))
dispatch(getLoginAttemptFailure(responseJson.message))
})
}
})
.catch((error) => {
console.log("error",error);
dispatch(getLoginAttempt(false))
dispatch(getLoginAttemptFailure(error))
})
}}
const getLoginAttempt = (isLoading) => {
return {
type: FETCH_LOGIN,isLoading: isLoading
};
}
const getLoginAttemptSuccess = (responseJson) => {
return {
type: FETCH_LOGIN_SUCCESSFUL,responseJson: responseJson
};
}
const getLoginAttemptFailure = (error) => {
return {
type: FETCH_LOGIN_FAILURE,error: error
};
}
Reducer示例(Login Reducer)
const initialState = {
loginResponseData: {},isLoggedIn: false,isLoginLoading: false,loginError: null
}
const loginReducer = (state = initialState,action) => {
switch (action.type) {
case FETCH_LOGIN:
return Object.assign({},state,{
isLoginLoading: true,isLoggedIn: false
})
case FETCH_LOGIN_SUCCESSFUL:
return Object.assign({},{
isLoginLoading: false,isLoggedIn: true,loginResponseData: action.responseJson
})
case FETCH_LOGIN_FAILURE:
return Object.assign({},loginError: action.error
})
default:
return state
}
}
然后在redux存储配置中将还原器与根还原器相连,并按如下所示连接至屏幕(登录屏幕)
export default connect(mapstatetoProps,mapDispatchToProps)(LoginScreen);