React中如何将class based component转换为使用Redux hooks的functional component
类组件转Redux Hooks函数式组件实现
核心改动说明
- 移除
connect高阶组件依赖,使用useSelectorHook直接从Redux store中读取error状态,替代原有的mapStateToProps配置 - 使用
useDispatchHook获取dispatch方法,直接调用触发loginaction,替代原connect的mapDispatchToProps绑定逻辑 - 原类组件中挂载在实例上的输入框ref,改用React内置的
useRefHook实现,完全消除this关键字的使用 - 原有条件渲染逻辑、交互逻辑、样式类名完全保留,功能和原类组件完全一致
import React, { useRef } from "react"; import { useSelector, useDispatch } from "react-redux"; import { AUTH_ERRORS, login } from "../ducks/client"; const Login = () => { // 从redux中获取错误状态 const error = useSelector(state => state.client.error); // 获取dispatch方法用于触发action const dispatch = useDispatch(); // 声明输入框ref绑定DOM元素 const jidRef = useRef(null); const passwordRef = useRef(null); const handleSubmit = (e) => { e.preventDefault(); if (jidRef.current.value.length && passwordRef.current.value.length) { dispatch(login(jidRef.current.value, passwordRef.current.value)); } }; // 证书错误的条件渲染 if (error === AUTH_ERRORS.CERTIFICATE) { return ( <div className="Page"> <h2>连接错误</h2> </div> ); } return ( <div className="Home Page"> <h2>登录</h2> <form className="form" onSubmit={handleSubmit}> {/* 账号密码错误的条件渲染 */} {error === AUTH_ERRORS.CREDENTIALS && ( <h4 className="formError">用户名或密码错误</h4> )} <label htmlFor="jid">用户名</label> <input ref={jidRef} type="text" name="jid" id="jid" placeholder="用户名" /> <label htmlFor="password">密码</label> <input ref={passwordRef} name="password" type="password" id="password" placeholder="密码" /> <div className="actions"> <input type="submit" value="登录" /> </div> </form> </div> ); }; export default Login;
内容的提问来源于stack exchange,提问作者Valley Computers
相关产品推荐
相关产品推荐

