【问题标题】:React-redux, connect function does not update the state with the new dataReact-redux,连接函数不使用新数据更新状态
【发布时间】:2015-12-23 03:08:43
【问题描述】:

我使用Redux 作为Flux 替代方案,React 用于视图层。我的应用程序的 ReactReduxreact-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/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;

reducers/RootReducer

'use strict';

import {combineReducers} from 'redux';
import sessionReducer from 'reducers/SessionReducer';

const rootReducer = combineReducers({
  session: sessionReducer
});

export default rootReducer;

【问题讨论】:

  • 你能展示你的状态吗?我认为因为你没有组合减速器,它看起来就像initialState 你也可以包括这个吗?
  • 嗨@Clarkie我更新了reducer并很好地说明了我如何组合reducer
  • 您是否尝试过在不使用 immutableJS 库的情况下让它工作?我只用过 react 的 immutability helpers redux
  • 您运行的是哪个版本的reduxreact-redux? 1.0 之前的版本可能存在问题。
  • 我不确定这是否与您遇到的问题直接相关,但您在componentWillMount 中登录到控制台的方式保证会为session 道具和商店中的session。对dispatch 的调用将同步更新存储,但在componentWillMount 完成之前,您不会看到新的session 属性。您可以通过在setTimeout 中记录this.props.session 而不是在调用dispatch 之后立即验证这一点吗?

标签: javascript reactjs redux


【解决方案1】:

问题在于从props 和存储中记录session 变量的方式。当您调度操作以更新状态时,它会同步更新存储,这就是为什么您在直接登录时会看到存储已更新的原因。但是,在对 componentWillMount 的调用完成并且 React 有机会赶上并重新渲染具有新状态的组件之前,react-redux 将无法更新 props。如果您在 componentWillMount 中调度操作并稍后记录 session 属性,您将看到它已更改以反映操作。

【讨论】:

    【解决方案2】:

    看起来你没有在 reducer 的动作处理程序中更改状态。只有casereturn state 以外的代码显示state.update('isSessionValid', () => false) — 它返回什么?如果它和之前的 state 是同一个对象,redux 不会因为不变性约定而改变任何东西。

    【讨论】:

    • stateImmutableJs 对象,updateMap 类的方法。这是full documentation。基本上update 函数将返回带有isSessionValid 的新Map 对象为false,最初它是null
    • @Max 并在使用此字段的客户端代码中,您是否明确区分 null 和 false?因为在 JavaScript 中都“计算为假”,这看起来可能有问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 2022-01-14
    相关资源
    最近更新 更多