正如标题所示,我正努力让我的Redux状态使用reducer进行更新。我也在使用Redux和React。在这种情况下,我使用Redux状态来保存用户是否使用JWT令牌登录的布尔值。我确信我已正确设置了Reducer,因为我可以控制注销掉初始验证状态,默认情况下设置为false。但是当我运行AUTH_USER操作告诉reducer更新状态以使authenticated = true时,没有任何反应。当记录auth的redux状态时,即使我已经为AUTH_USER运行了该操作,它仍然是假的。它似乎正确地进入reducer中的switch语句,因为console.log显示在终端中。我从头部组件的componentDidMount生命周期方法获取控制台日志,该方法呈现在我的React应用程序的每个部分。
Reducers的Index.js(/src/reducers/index.js)
import { combineReducers } from 'redux';
import authReducer from './reducer_auth';
const rootReducer = combineReducers({
auth: authReducer
});
export default rootReducer;
身份验证Reducer(/src/reducers/reducer_auth.js)
import { AUTH_USER, DEAUTH_USER } from '../actions/types';
export default function (state = { authenticated: false, error: "" },
action) {
switch(action.type) {
case AUTH_USER:
console.log('THIS DOES SHOW UP IN CONSOLE')
return {...state, error: "", authenticated: true };
case DEAUTH_USER:
return {...state, error: "", authenticated: false };
default:
return state;
}
}
用于登录的Action Creator(/src/actions/index.js)
import axios from 'axios';
import history from '../utils/historyUtils';
import { AUTH_USER, DEAUTH_USER } from './types';
const ROOT_URL = 'http://localhost:8888';
export function signInUser(username, password) {
const signInRequest = axios.post(`${ROOT_URL}/wp-json/jwt-auth/v1/token`, {
"username": username,
"password": password
});
return (dispatch) => {
return signInRequest.then(response => {
localStorage.setItem('token', JSON.stringify(response.data.token));
dispatch({
type: AUTH_USER,
payload: { authenticated : true }
})
history.push('/');
history.go();
})
}
}
标题组件(/src/containers/header.js)
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { signOutUser } from '../actions';
import '../styles/header.css';
class Header extends Component {
componentDidMount() {
console.log('authenticated from header: ', this.props.authenticated)
}
handleLogout(event) {
event.preventDefault();
localStorage.removeItem('token');
}
render() {
return (
<div className="container">
<header>
<div id="branding">
<h1><Link to="/">INSERT BRAND HERE</Link></h1>
</div>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/contact">Contact</Link></li>
<li><Link to="/services">Services</Link></li>
<li><Link to="/Portfolio">Portfolio</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/blog">Blog</Link></li>
{/* {this.props.authenticated ? <li>Logout</li> : <li><Link to="/signin">Login</Link></li>} */}
<li><Link to="/signin">Login</Link></li>
</ul>
</nav>
</header>
</div>
);
}
}
function mapStateToProps(state) {
return {
authenticated: state.auth
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
signOutUser
}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Header);
保存路由的Index.js(/src/index.js)
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import reduxThunk from 'redux-thunk';
import reducers from './reducers';
import Home from './components/home';
import About from './components/about';
import Blog from './containers/blog';
import Contact from './components/contact';
import Portfolio from './components/portfolio';
import Services from './components/services';
import registerServiceWorker from './registerServiceWorker';
import SignIn from './containers/signIn_form';
const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<div>
<Switch>
<Route path="/about" component={About} />
<Route path="/blog" component={Blog} />
<Route path="/contact" component={Contact} />
<Route path="/portfolio" component={Portfolio} />
<Route path="/services" component={Services} />
<Route path="/signin" component={SignIn} />
<Route path="/" component={Home} />
</Switch>
</div>
</BrowserRouter>
</Provider>
, document.getElementById('root'));
registerServiceWorker();
如果有人能帮助解决这个问题,我将非常感激!
答案 0 :(得分:0)
感谢大家的评论,你们都很棒!它帮助我意识到我在动作创建者中用于编程导航的历史npm模块由于某种原因重置了我的redux状态(如果有人好奇,这里是历史模块的github的链接:https://github.com/ReactTraining/history)。从我的应用程序中删除模块后,redux状态现在更新并保持按预期更新。