简体   繁体   English

Redux - 组件不使用 connect() 重新渲染

[英]Redux - Component not re-rendering using connect()

I have a component that needs to hide/show content based on whether the user is logged in or not.我有一个组件需要根据用户是否登录来隐藏/显示内容。 My Redux logger is showing the proper state change but the connected component is not re-rendering.我的 Redux 记录器显示正确的状态更改,但连接的组件没有重新渲染。 At first I figured it was a mutation issue, however after attempting the same thing with immutable.js and redux-starter-kit 's createReducer with no success, I figured otherwise.起初我认为这是一个突变问题,但是在使用immutable.jsredux-starter-kitcreateReducer尝试同样的事情但没有成功之后,我认为不是这样。

It's my understanding that when using mapStateToProps the component should re-render the same as if it were local state.我的理解是,当使用mapStateToProps ,组件应该像本地状态一样重新渲染。

Reducer:减速器:

export default (
  state = {
    hasAuth: false,
  },
  action
) => {
  switch (action.type) {
    case AUTH_LOADED:
      return { ...state, hasAuth: true }
    default:
      return state;
  }
};

Component:成分:

class Screen extends PureComponent {
  render() {
    return (
      <Fragment>
        {this.props.hasAuth && <Text>Logged In</Text>}
      </Fragment>
    );
  }
}

export default connect(state => ({
  hasAuth: state.auth.hasAuth,
}))(Screen);

Root Reducer根减速机

import { createStore, applyMiddleware, combineReducers } from 'redux';
import { batchedSubscribe } from 'redux-batched-subscribe';
import thunk from 'redux-thunk';
import reduxMulti from 'redux-multi';
import logger from 'redux-logger';

import auth from './reducers/auth';

const rootReducer = combineReducers({
  auth,
});

const createStoreWithMiddleware = applyMiddleware(thunk, reduxMulti, logger)(
  createStore
);

const createStoreWithBatching = batchedSubscribe(fn => fn())(
  createStoreWithMiddleware
);

export default createStoreWithBatching(rootReducer);

You have to wire up Redux in Combination with batchedSubscribe correctly.您必须正确地将 Redux 与batchedSubscribe结合使用。 Here are the docs with a short guide: https://github.com/tappleby/redux-batched-subscribe以下是带有简短指南的文档: https : //github.com/tappleby/redux-batched-subscribe

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

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