首页 > 解决方案 > 如何在 React 的类组件中使用 mapStateToProps?

问题描述

功能组件中的 Login.js

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


const Login = ({ login, isAuthenticated }) => {
    return (
        <div>
           // some code here
        </div>
    );
};

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

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

如何在类组件中使用上面的 mapStateToProps 函数,就像我在功能组件中使用的一样?

类组件中的 Login.js

import React, {Component} from "react";

class Login extends Component{
    constructor(props) {
        super(props);
        this.state = {
            search:'',
        }
    }
    render() {
        return(
        <div> 
             //some code here
        </div>
        )
     }
}
export default Login;

标签: reactjsreact-redux

解决方案


在类组件mapStateToProps中和函数式组件的工作方式相同,我觉得只是在一些语法或调用方式上有所不同。

mapStateToProps 函数是使用 function 关键字 (function mapState(state) { } ) 还是箭头函数 (const mapState = (state) => { } ) 编写的,这并不重要 - 无论哪种方式,它的工作方式都是一样的。

类组件mapStateToProps

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() {
        const { isAuthenticated } = this.props;
        return(
        <div> 
             //some code here
        </div>
        )
     }
}

function mapStateToProps(state) {
  const { isAuthenticated } = state.auth.isAuthenticated
  return { isAuthenticated }
}

export default connect(mapStateToProps)(Login)

如您所见,只有 1 个主要区别是:在Class 组件中,我们从中读取值isAuthenticatedthis.props而在Functional 组件中,我们将值作为参数获取。

有关信息,请阅读更多关于mapStateToPropshttps://react-redux.js.org/using-react-redux/connect-mapstate


推荐阅读