React-Redux如何将函数组件改写为功能等价的类组件
React-Redux 函数组件转等价类组件实现
你可以使用react-redux提供的connect高阶组件替代hooks能力,结合类组件生命周期实现和原函数组件功能完全一致的效果,完整代码如下:
import React from "react"; import { connect } from "react-redux"; import { getTodoList } from "./redux/action/todoList"; class App extends React.Component { // 对应原代码空依赖useEffect,仅在组件首次挂载后执行 componentDidMount() { this.props.dispatch(getTodoList()); } render() { // 从props取注入的redux状态,对应原useSelector的取值结果 const { todoList } = this.props; console.log(todoList); return ( <div className="App"> {todoList.data.length > 0 ? todoList.data.map((obj) => { return ( <> <div className="card"> <div className="content"> <div className="header">{obj.title}</div> </div> </div> </> ); }) : ""} </div> ); } } // 映射store状态到组件props,等价于useSelector的取值逻辑 const mapStateToProps = (state) => ({ todoList: state.todoList }); // connect包裹组件导出,默认注入dispatch方法到组件props export default connect(mapStateToProps)(App);
能力对应关系
useDispatch():类组件无需单独调用hook获取dispatch方法,connect高阶组件默认会将dispatch注入到组件props中,直接通过this.props.dispatch即可调用useSelector(state => state.todoList):逻辑完全迁移到mapStateToProps函数中,负责从全局store提取组件需要的状态,映射后可在组件内通过this.props.todoList访问- 空依赖数组的
useEffect:和类组件componentDidMount生命周期执行时机完全一致,仅在组件首次挂载完成后触发一次待办列表请求 - 渲染逻辑完全和原函数组件保持一致,没有改动原有DOM结构、class名、条件判断和遍历规则,运行效果完全等价
内容的提问来源于stack exchange,提问作者Varma 7799
相关产品推荐
相关产品推荐

