Max*_*Max 3 javascript reactjs redux
我正在使用它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);
Run Code Online (Sandbox Code Playgroud)
动作/ 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)));
};
}
Run Code Online (Sandbox Code Playgroud)
减速器/ 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;
Run Code Online (Sandbox Code Playgroud)
减速器/ RootReducer
'use strict';
import {combineReducers} from 'redux';
import sessionReducer from 'reducers/SessionReducer';
const rootReducer = combineReducers({
session: sessionReducer
});
export default rootReducer;
Run Code Online (Sandbox Code Playgroud)
问题在于从存储中session记录变量的方式props.当您将操作分派给更新状态时,它会同步更新存储,这就是您在直接登录时看到存储已更新的原因.但是,react-redux将无法更新props,直到调用componentWillMount完成并且React有机会赶上并重新呈现具有新状态的组件.如果您稍后调度操作componentWillMount并记录session道具,您将看到它已更改以反映该操作.
| 归档时间: |
|
| 查看次数: |
6750 次 |
| 最近记录: |