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

React Redux中connect的使用方法及Webpack处理其装饰器的预设问题

Hey there! Let's tackle your React Redux and Webpack questions step by step—no jargon overload, promise.

1. How to Use connect in React Redux

The connect function is how you hook your React components up to the Redux store. There are a couple of ways to use it, including the decorator syntax you tried. Here's a breakdown:

Basic Steps (Non-Decorator Syntax)

  • First, import connect from react-redux:
    import { connect } from 'react-redux';
    import React from 'react';
    
  • Define mapStateToProps: This function pulls data from the store and passes it as props to your component.
    const mapStateToProps = (state) => {
      return {
        // Example: pass the 'user' slice of state as a prop
        user: state.user
      };
    };
    
  • Define mapDispatchToProps (optional): This lets you pass Redux action creators as props to trigger state changes. You can either write it as a function or pass an object directly:
    // Option 1: Object syntax (simpler for most cases)
    import { fetchUser } from './actions';
    const mapDispatchToProps = { fetchUser };
    
    // Option 2: Function syntax (if you need access to dispatch directly)
    const mapDispatchToProps = (dispatch) => {
      return {
        fetchUser: () => dispatch(fetchUser())
      };
    };
    
  • Connect your component: Wrap your class component with connect:
    class App extends React.Component {
      render() {
        // Use this.props.user and this.props.fetchUser here
        return <div>Hello {this.props.user?.name}</div>;
      }
    }
    
    export default connect(mapStateToProps, mapDispatchToProps)(App);
    

Using the Decorator Syntax (Like Your Code Example)

If you prefer the decorator approach, the setup is similar, but you need to make sure your tooling supports decorators (we'll cover that in the next section). Here's the correct decorator usage:

import { connect } from 'react-redux';
import React from 'react';
import { fetchUser } from './actions';

const mapStateToProps = (state) => ({ user: state.user });
const mapDispatchToProps = { fetchUser };

@connect(mapStateToProps, mapDispatchToProps)
class App extends React.Component {
  render() {
    return <div>Hello {this.props.user?.name}</div>;
  }
}

export default App;

Note: Your original code had connect(store) which is incorrect—connect takes mapStateToProps and mapDispatchToProps (or null if you don't need either), not the store directly.

2. Webpack Preset/Plugin for connect Decorators & Fixing the "No Reaction" Issue

The reason your Webpack build isn't doing anything (or your decorator isn't working) is that JavaScript doesn't natively support decorators yet—you need Babel to transpile that syntax. Here's what you need to do:

Step 1: Install Required Babel Packages

First, install the necessary Babel plugins:

npm install --save-dev @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties

Step 2: Configure Babel

Update your .babelrc or babel.config.json file to enable the decorator plugin (note: decorators need to be enabled before class properties):

{
  "presets": ["@babel/preset-react", "@babel/preset-env"],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }]
  ]
}

Step 3: Check Your Webpack Config

Make sure your Webpack config is set up to use Babel for transpiling .jsx/.js files. Here's a snippet of the module rules:

module.exports = {
  // ... other config
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx']
  }
};

Why Your Original Code Might Not Be Working

  • You used connect(store) instead of passing mapStateToProps/mapDispatchToProps (or null if you don't need state/dispatch).
  • Your Webpack/Babel setup wasn't configured to transpile decorator syntax, so the code was being ignored or causing silent errors.
  • Double-check that you've wrapped your app in a Provider component from react-redux—without this, connect won't have access to the store:
    import { Provider } from 'react-redux';
    import { createStore } from 'redux';
    import rootReducer from './reducers';
    import App from './App';
    
    const store = createStore(rootReducer);
    
    ReactDOM.render(
      <Provider store={store}>
        <App />
      </Provider>,
      document.getElementById('root')
    );
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:07:04