我正在使用 Redux
作为 Flux
的替代方案,并使用 React
作为 View 层。我的应用程序的 React
和 Redux
与 react-redux
connect()
方法绑定(bind)。
当运行应用程序时,它会在组件挂载并且 redux 返回正确状态时分派(dispatch)操作。然而 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/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)));
};
}
reducers/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;
reducer /RootReducer
'use strict';
import {combineReducers} from 'redux';
import sessionReducer from 'reducers/SessionReducer';
const rootReducer = combineReducers({
session: sessionReducer
});
export default rootReducer;
最佳答案
问题在于 session
变量从 props
和存储中记录的方式。当您将操作分派(dispatch)到更新状态时,它会同步更新商店,这就是为什么您在直接登录时看到商店已更新的原因。但是,在对 componentWillMount
的调用完成之前,react-redux 将无法更新 props,并且 React 有机会 catch 并使用新状态重新渲染组件。如果您在 componentWillMount
中发送操作并稍后记录 session
属性,您将看到它已更改以反射(reflect)操作。
关于javascript - React-redux,连接函数不使用新数据更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32779552/