简体   繁体   English

状态改变时Redux不会更新React组件

[英]Redux won't update React component when state change

I'm trying to get my simple Redux React test work. 我正在尝试进行简单的Redux React测试工作。 I'm really new to both Redux and React. 我真的是Redux和React的新手。 I've been reading through Redux documentation and in Troubleshooting section, it said that reducer should return new object everytime. 我一直在阅读Redux文档,在“ 疑难解答”部分中说,减速器每次都应返回新对象。 In my case, I think I'm returning new object... 就我而言,我想返回的是新对象...

Any suggestions are appreciate! 任何建议,感激不尽!

My reducer: 我的减速器:

const memberOpReducer = (state = {isLoading: true, isLoggedIn: false}, action) => {
  switch(action.type) {
    case 'CHECK_LOGIN_STATUS':
      return {
        isLoading: true
      }
    case 'LOGIN_STATUS':
      return {
        isLoading: false,
        isLoggedIn: action.response.status === 'connected',
        response: action.response
      };
    default:
      return state;
  }
};

My actions: 我的动作:

const checkLoginStatus = () => ({
  type: 'CHECK_LOGIN_STATUS'
});

const loginStatus = response => ({
  type: 'LOGIN_STATUS',
  response: response
});

const getLoginStatus = (options = {}) => dispatch => {
  dispatch(checkLoginStatus());
  FB.getLoginStatus(function (response) {
    dispatch(loginStatus(response));
  }, options);
}

Please have a look at this working pen: https://codepen.io/mrducnguyen/pen/rGxpGR 请看一下这支工作笔: https : //codepen.io/mrducnguyen/pen/rGxpGR

The problem is in your mapStateToProps function: 问题出在您的mapStateToProps函数中:

// Your function, just for reference
const mapStateToProps = state => {
  return {
    isLoggedIn: state.isLoggedIn === undefined ? false : state.isLoggedIn,
    isLoading: state.isLoading === undefined ? true : state.isLoading,
    response: state.response
  }
}

You're accessing state.isLoggedIn , but you should be accessing state.memberOpReducer.isLoggedIn , because you used combineReducers which namespaces all of the fields of that reducer under the reducer's name. 您正在访问state.isLoggedIn ,但是您应该在访问state.memberOpReducer.isLoggedIn ,因为您使用了combineReducers ,它以reducer的名称命名该reducer的所有字段的名称空间。 Same for all the other fields, of course. 当然,所有其他字段都相同。

// Fixed version
const mapStateToProps = state => {
  return {
    isLoggedIn: state.memberOpReducer.isLoggedIn,
    isLoading: state.memberOpReducer.isLoading,
    response: state.memberOpReducer.response
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM