即使我的代码在文档中看似正确,Reducer中的状态也不会更新。我将值记录到我的化简器中,type
返回SIGNIN_USER
,current state
返回false
,而payload
返回true
。
这是我的减速器
import { SIGNIN_USER } from "../constants/action-types";
export default (state = {
isAuthenticated: false,
}, action) => {
switch (action.type) {
case SIGNIN_USER:
console.log('Type: ' + action.type);
console.log('Reducer State: ' + state.isAuthenticated);
console.log('Reducer Payload: ' + action.payload.authenticated);
return {
...state,
isAuthenticated: action.payload.authenticated
};
default:
return state;
}
};
当我将isAuthenticated状态硬编码为true时,它可以工作。但是,当我将其设置为false并想要在我的Reducer中对其进行更新时,它不会得到更新。 我真的不明白我在做什么错..有人可以帮我吗?
这也是我的动作:
export const signinUser = ({ username, password }) => async dispatch => {
new Promise(async (resolve, reject) => {
try {
const req = await axios
/* Make API Post call with user data. */
.post('api/user/login', {
username: username,
password: password
});
const token = req.data.data.auth_token;
const success = req.data.success;
let authenticated = true;
dispatch({
type: 'SIGNIN_USER',
payload: { authenticated }
});
if (success){
localStorage.setItem('jwtToken', token);
localStorage.setItem('loggedIn', true);
window.location.assign('/');
}
resolve();
} catch (e) {
console.log(e);
reject(e);
}
});
};
需要检查状态的我的组件:
import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import { connect } from 'react-redux';
const privateRouter = ({component: Component, isAuthenticated, ...rest }) => {
console.log('PrivateRoute privateRouter: ' + isAuthenticated);
return (
<Route
{...rest}
render={props =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)}
/>
)
};
const mapStateToProps = ({ auth }) => ({
isAuthenticated: auth.isAuthenticated
});
export default connect(mapStateToProps)(privateRouter);
我的商店:
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import authReducer from '../reducers/index';
const rootReducer = combineReducers({
auth: authReducer
});
const store = createStore(
rootReducer,
compose(
applyMiddleware(thunk),
window.REDUX_DEVTOOLS_EXTENSION
? window.REDUX_DEVTOOLS_EXTENSION()
:f => f
)
);
export default store;
这是我称为signinUser的函数:
handleSubmit = (e) => {
e.preventDefault();
const { username, password } = this.state;
this.props.signinUser({username, password});
};
答案 0 :(得分:0)
让我们全面了解您的动作创建者,也许我们可以与之合作。.
答案 1 :(得分:0)
您可以尝试这种方式,但是我不能说这会起作用
import { SIGNIN_USER } from "../constants/action-types";
export default (state = {
isAuthenticated: false,
}, action) => {
switch (action.type) {
case SIGNIN_USER:
//console.log('Type: ' + action.type);
//console.log('Reducer State: ' + state.isAuthenticated);
//console.log('Reducer Payload: ' + action.payload.authenticated);
if(action.payload.authenticated){
return {
...state,
isAuthenticated
};
}
return {
...state,
(!isAuthenticated)
};
default:
return state;
}
};