我将Redux
其用作Flux
替代方案并React
用于视图层。我的应用程序React
与方法Redux
绑定react-redux
connect()
。在运行应用程序时,它会在组件挂载并且 redux 返回正确状态时调度操作。但是redux-logger
,商店已使用新状态更新的控制台中的日志,在组件中检查this.props.session
时仍显示旧状态。我猜我没有connect
正确使用该方法,但是我也无法定义它的问题。有谁知道发生了什么?
容器/应用
'use strict';
import React from 'react';
import {connect} from 'react-redux';
import {fetchUserSession} from 'actions/SessionActions';
class App extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
const {dispatch, session} = this.props;
dispatch(fetchUserSession());
console.log(session);
// logs:
// Object {currentUserId: null, errorMessage: null, isSessionValid: null}
// store is bound to window, and the initial state is ImmutabeJS object
console.log(window.store.getState().session.toJS());
// logs:
// Object {currentUserId: null, errorMessage: null, isSessionValid: false}
// as you might noticed the isSessionValid is changed to false
}
render() {
// html here
}
}
function mapStateToProps(state){
return {
session: state.session.toJS()
};
}
export default connect(mapStateToProps)(App);
动作/Actions.js
'use strict';
import fetch from 'isomorphic-fetch';
export const SESSION_REQUEST = 'SESSION_REQUEST';
export const SESSION_SUCCESS = 'SESSION_SUCCESS';
export function requestSession() {
return {
type: SESSION_REQUEST
};
}
export function receiveSession(user) {
return {
type: SESSION_REQUEST,
user
};
}
export function fetchUserSession() {
return dispatch => {
dispatch(requestSession());
return fetch(`http://localhost:5000/session`)
.then((response) => {
if (response.status === 404) {
dispatch(raiseSessionFailure(response));
}
return response.json();
})
.then(userData => dispatch(receiveSession(userData)));
};
}
减速器/SessionReducer.js
'use strict';
import {fromJS} from 'immutable';
// UPDATE!!!
// here is the initial state
const initialState = fromJS({
currentUserId: null,
errorMessage: null,
isSessionValid: null
});
function sessionReducer(state = initialState, action) {
switch (action.type) {
case 'SESSION_REQUEST':
return state.update('isSessionValid', () => false);
case 'SESSION_SUCCESS':
console.log('Reducer: SESSION_SUCCESS');
return state;
case 'SESSION_FAILURE':
console.log('Reducer: SESSION_FAILURE');
return state;
default:
return state;
}
}
export default sessionReducer;
减速器/RootReducer
'use strict';
import {combineReducers} from 'redux';
import sessionReducer from 'reducers/SessionReducer';
const rootReducer = combineReducers({
session: sessionReducer
});
export default rootReducer;