reactjs - 如何在 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;
解决方案
在类组件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 组件中,我们从中读取值isAuthenticated
,this.props
而在Functional 组件中,我们将值作为参数获取。
有关信息,请阅读更多关于mapStateToProps
。https://react-redux.js.org/using-react-redux/connect-mapstate
推荐阅读
- reactjs - 反应网格布局不更新高度
- javascript - 在 vanilla javascript 中将函数扩展到 querySelector
- adfs - 为 ADFS SSO 登录页面实施自定义 HTML、CSS 和 JS
- java - 如何将全局变量从一个测试类传递到另一个测试类并在 selenium 的下拉列表中选择该值?
- php - 如果 foreach 中的语句只检查最后一个值
- c# - UWP:不要缩放滚动查看器内媒体播放器元素的媒体传输控件
- javascript - JS 没有响应更新的 txt 文件
- java - 试图解压缩 BC1 纹理压缩的加扰块
- reactjs - 棱镜与 Gatsby 的集成导致构建中未定义窗口
- c++ - 用 C++ 中的模板方法覆盖类方法