You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化多组件连接React Redux Store的重复代码?

Simplify Redux Component Connections (Avoid Repetitive Code!)

Great question—copy-pasting connect logic and action imports across every component is such a tedious hassle, and I’ve definitely been there! Luckily, there are a few solid approaches to cut down on that repetition, depending on whether you want to stick with the classic connect API or move to the modern, recommended Redux patterns.

1. Switch to Redux Toolkit + React-Redux Hooks (Best Practice)

If you haven’t already, Redux Toolkit (RTK) is the official, opinionated toolkit for Redux that eliminates almost all boilerplate. Pair it with React-Redux’s useSelector and useDispatch hooks, and you can ditch connect entirely for functional components.

Here’s how it works:

  • First, define your slice (which includes your reducer and actions) with createSlice:
    // features/exampleSlice.js
    import { createSlice } from '@reduxjs/toolkit';
    
    const initialState = {
      isSomethingWritten: false
    };
    
    const exampleSlice = createSlice({
      name: 'example',
      initialState,
      reducers: {
        writeSomething: (state) => {
          state.isSomethingWritten = true; // RTK allows mutable syntax (it uses Immer under the hood)
        }
      }
    });
    
    export const { writeSomething } = exampleSlice.actions;
    export default exampleSlice.reducer;
    
  • Then, in any component, you can directly access the store and dispatch actions without connect:
    import { useSelector, useDispatch } from 'react-redux';
    import { writeSomething } from './features/exampleSlice';
    
    function MyComponent() {
      const isSomethingWritten = useSelector(state => state.example.isSomethingWritten);
      const dispatch = useDispatch();
    
      return (
        <button onClick={() => dispatch(writeSomething())}>
          {isSomethingWritten ? 'Done' : 'Write Something'}
        </button>
      );
    }
    
    export default MyComponent;
    

No more copying mapStateToProps or mapDispatchToProps—each component just grabs exactly what it needs with the hooks.

2. Create a Reusable Higher-Order Component (HOC)

If you need to keep using connect (e.g., for class components), wrap the common connect logic into a reusable HOC. This way, you only write the base mapState/mapDispatch once, and customize it per component if needed.

Example:

// withStore.js
import { connect } from 'react-redux';
import { writeSomething } from './actions';

// Default mapState and mapDispatch
const defaultMapState = state => ({ ...state });
const defaultMapDispatch = dispatch => ({
  writeSomething: () => dispatch(writeSomething)
});

// Create a reusable HOC
export const withStore = (
  Component,
  customMapState = defaultMapState,
  customMapDispatch = defaultMapDispatch
) => {
  return connect(customMapState, customMapDispatch)(Component);
};

Then, in your components:

// App.js
import { withStore } from './withStore';

function App(props) {
  return <button onClick={props.writeSomething}>Click Me</button>;
}

// Use the default HOC
export default withStore(App);

// For a component that needs custom state mapping:
function OtherComponent(props) {
  return <div>{props.specificValue}</div>;
}

export default withStore(OtherComponent, state => ({ specificValue: state.someKey }));

This lets you reuse the base logic, while still allowing overrides when a component needs something unique.

3. Bind Actions Once and Reuse Them

Another quick win is to use bindActionCreators to pre-bind your actions to dispatch once, then import the bound actions anywhere.

Example:

// boundActions.js
import { bindActionCreators } from 'redux';
import { writeSomething } from './actions';
import store from './store';

const { dispatch } = store;
export const boundActions = bindActionCreators({ writeSomething }, dispatch);

Then, in components, you can skip mapDispatchToProps entirely:

import { connect } from 'react-redux';
import { boundActions } from './boundActions';

const mapStateToProps = state => ({ ...state });

function App(props) {
  return <button onClick={boundActions.writeSomething}>Click Me</button>;
}

export default connect(mapStateToProps)(App);

This cuts down on importing actions and writing mapDispatch for every component.


内容的提问来源于stack exchange,提问作者randomboiguyhere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 12:04:06