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

React 类组件中如何像函数组件一样使用 mapStateToProps?

改造步骤

你只需要在现有类组件的基础上做几处简单修改即可,mapStateToProps的写法和函数组件场景完全一致,不需要调整逻辑:

  1. 头部引入 redux 相关依赖
  2. 定义和之前完全相同的mapStateToProps
  3. 用connect高阶组件包裹类组件后导出
  4. 类组件内部通过this.props访问Redux注入的isAuthenticated状态和login方法

完整改造后的代码

import React, {Component} from "react";
import { connect } from 'react-redux';
import { login } from '../actions/auth';

class Login extends Component{
    constructor(props) {
        super(props);
        this.state = {
            search:'',
        }
    }
    render() {
        // 示例:访问redux注入的状态和方法,和函数组件的props完全对应
        const { isAuthenticated, login } = this.props;
        return(
        <div> 
             //some code here
        </div>
        )
     }
}

const mapStateToProps = state => ({
    isAuthenticated: state.auth.isAuthenticated
});

export default connect(mapStateToProps, { login })(Login);

补充说明

mapStateToProps返回的所有属性、connect第二个参数传入的所有action creator,都会被注入到类组件的props中,直接通过this.props.xxx调用即可,逻辑和函数组件中直接从参数解构props的规则完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:09:07