如何从商店获得状态的价值?
我已经尝试使用store.getState()。isLoggedIn,但是没有用:
import * as actions from 'actions/actions'
import store from 'store/store'
store.dispatch(actions.login(this.state.username,this.state.password)).then(() => {
state = store.getState();
alert(state.isLoggedIn);
});
我正在尝试获取状态“ isLoggedIn”的值,但它返回“ undefined”。如何从商店正确获取状态值?
这是我的源代码
减速器:
const INITIAL_STATE={
isLoggedIn:false,
isLoading:false,
userData:{},
error:undefined
}
export default function auth(state=INITIAL_STATE,action){
console.log(action.type);
switch (action.type) {
case 'LOGIN_ATTEMPT':
return{
...state,
isLoading:true,
isLoggedIn:false
}
break;
case 'LOGIN_SUCCESS':
return {
...state,
isLoading:false,
isLoggedIn:true,
userData:action.userData,
error:undefined
}
break;
case 'LOGIN_FAILED':
return{
...state,
isLoading:false,
isLoggedIn:false,
error:action.error
}
break;
case 'LOGOUT':
return{
...state,
isLoading:false,
isLoggedIn:false
}
break;
default:
return state
}
}
动作:
export function isLoading(bool:Boolean){
return{
type:'LOGIN_ATTEMPT',
isLoading:bool
}
}
export function loginSuccess(userData:Object){
return{
type:'LOGIN_SUCCESS',
userData
}
}
export function loginFailed(error:Object){
return{
type:'LOGIN_FAILED',
error
}
}
export function login(uname,pass){
return dispatch => {
dispatch(isLoading(true));
return fetch('http://192.168.99.1:5000/user/login',{
method:'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify({
username:uname
})
})
.then((response) => {
if(response.status < 300){
dispatch(isLoading(false))
response.json().then((responseJSON) => {
if(responseJSON['message'] == "True" && bcrypt.compareSync(pass, responseJSON['hash']) ){
console.log("responseJSON",responseJSON);
dispatch(loginSuccess(responseJSON));
}
else{
dispatch(isLoading(false))
dispatch(loginFailed(responseJSON.message))
}
})
}
else{
response.json().then((responseJSON) => {
console.log("responseJSON",responseJSON);
dispatch(isLoading(false))
dispatch(loginFailed(responseJSON.message))
})
}
})
.catch((error) => {
console.log("error",error);
dispatch(isLoading(false))
dispatch(loginFailed(error))
})
}
}
商店:
import {combineReducers} from 'redux'
import auth from './authReducer'
import {createStore,applyMiddleware} from 'redux'
import thunk from 'redux-thunk';
const rootReducer = combineReducers({
auth
})
let store = createStore(rootReducer,applyMiddleware(thunk))
export default store;
答案 0 :(得分:0)
您正在使用combineReducers
生成rootReducer
。
combinedReducers()所产生的状态在每个键值传递给CombineReducers()的键名下的状态命名空间
所以store.getState()
将返回这样的对象
{ auth:
{ isLoggedIn:false,
isLoading:false,
userData:{},
error:undefined
}
}
要引用isLoggedIn
,您必须做alert(state.auth.isLoggedIn);
答案 1 :(得分:-1)
我能够使用JSON.stringify查看数据
JSON.stringify(store.getState())
它返回json数据。使用此方法可以轻松查看对象