【问题标题】:Redux - Component not re-rendering using connect()Redux - 组件不使用 connect() 重新渲染
【发布时间】:2019-02-10 22:51:43
【问题描述】:

我有一个组件需要根据用户是否登录来隐藏/显示内容。我的 Redux 记录器显示正确的状态更改,但连接的组件没有重新渲染。起初我认为这是一个突变问题,但是在尝试使用 immutable.js 和 redux-starter-kit 的 createReducer 没有成功之后,我认为不是这样。

据我了解,当使用 mapStateToProps 时,组件应该重新渲染,就像它是本地状态一样。

减速机:

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

组件:

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);

【问题讨论】:

  • 您将Screen 的hasAuth 属性设置为state.auth.hasAuth,但在reducer 中您似乎更新了state.hasAuth,而不是state.auth.hasAuth。
  • 这是你唯一的减速器吗?如果不是,您的combineReducers 看起来如何?
  • @Tholle auth 实际上是我的减速器名称。我正在使用combineReducers,因此它使用名称作为属性将其嵌套一层。我可以访问我的组件中的hasAuth,它只是不显示更改,除非重新安装组件或我forceUpdate()。
  • @GeraltDieSocke 用我的根减速器更新了问题。我删除了所有不相关的减速器。
  • 我不确定 redux 是否真的像这样正确连接。如果您像文档中所示那样连接batchedSubscribe 怎么办:github.com/tappleby/redux-batched-subscribe 那么它工作了吗?

标签: javascript reactjs react-native redux


【解决方案1】:

您必须将 Redux 与 batchedSubscribe 正确连接。 以下是带有简短指南的文档:https://github.com/tappleby/redux-batched-subscribe

【讨论】:

    猜你喜欢
    • 2017-04-10
    • 2017-08-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2018-03-24
    • 1970-01-01
    • 2020-06-01
    相关资源
    最近更新 更多