使用React的Class组件将其连接到React-Redux

在React-Redux的说明页面中,主要使用函数式组件作为例子进行解释,而很少看到如何在类组件中进行连接的具体例子。对于熟悉这个问题的人来说,可能是个微不足道的问题,但对我个人来说,有点困扰,所以我决定写一篇文章。

如果我们想要在组件挂载和卸载等特定时机调用生命周期方法的时候,如果不使用 Class Component 的话可能会很不方便(可能是我的误解),或者我们原本将组件定义为 Class Component,并且想要将其连接到 React-Redux 中等等,那么在使用React Hooks于16.8版本中新增的功能的情况下,我们可能也可以通过 Functional Component 实现相同的功能。

准备

img3.png

请用中文表达以下内容,只需要一种选项:

实际上改写

这次的修改将针对examples/basic/src/components/Counter.js这个文件中定义的Component进行。

经过一番不断尝试和错误,结果只有这个地方需要重新写入。

import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { increment, decrement } from '../actions/counter'

-const Counter = (props) => (
-  <div>
-    Counter: {props.count}
-    <button onClick={props.increment}>+</button>
-    <button onClick={props.decrement}>-</button>
-  </div>
-)
+class Counter extends React.Component {
+  constructor(props) {
+    super(props);
+  }
+  render(){
+    return (
+      <div>
+        Counter: {this.props.count}
+        <button onClick={this.props.increment}>+</button>
+        <button onClick={this.props.decrement}>-</button>
+      </div>
+    );
+  }
+}

Counter.propTypes = {
  count: PropTypes.number,
  increment: PropTypes.func.isRequired,
  decrement: PropTypes.func.isRequired,
}

const mapStateToProps = state => ({
  count: state.count,
})

const mapDispatchToProps = dispatch => ({
  increment: () => dispatch(increment()),
  decrement: () => dispatch(decrement()),
})

export default connect(mapStateToProps, mapDispatchToProps)(Counter)

作为主要的变更点:
1. 主体JSX被指定为render()的返回值。
2. 箭头函数参数将从constructor()传递给super()。
3. 传递给super的props在类内部将成为this.props。

bannerAds