【发布时间】:2021-11-12 11:12:04
【问题描述】:
如何将此class based component 转换为functional component。因为这是一个基于类的简单组件,我想将react class based component 转换为functional component 和redux hooks。我想使用redux hoooks在这个组件中。我对class based components 不满意,因为this 关键字对我来说是最令人困惑的词。我想使用来自react-redux 钩子的useSelector hook 和useDispatch。在我使用条件渲染的这个组件中
import React from "react";
import { connect } from "react-redux";
import { AUTH_ERRORS, login } from "../ducks/client";
class Login extends React.Component {
render() {
if (this.props.error === AUTH_ERRORS.CERTIFICATE) {
return (
<div className="Page">
<h2>Connection error</h2>
</div>
);
}
return (
<div className="Home Page">
<h2>Login</h2>
<form className="form" onSubmit={this.handleSubmit}>
{this.props.error === AUTH_ERRORS.CREDENTIALS && (
<h4 className="formError">Incorrect username or password</h4>
)}
<label htmlFor="jid">Username</label>
<input
ref={(el) => (this._jid = el)}
type="text"
name="jid"
id="jid"
placeholder="Username"
/>
<label htmlFor="password">Password</label>
<input
ref={(el) => (this._password = el)}
name="password"
type="password"
id="password"
placeholder="Password"
/>
<div className="actions">
<input type="submit" value="Log in" />
</div>
</form>
</div>
);
}
handleSubmit = (e) => {
e.preventDefault();
if (this._jid.value.length && this._password.value.length) {
this.props.login(this._jid.value, this._password.value);
}
};
}
const mapStateToProps = (state) => ({
error: state.client.error,
});
export default connect(mapStateToProps, { login })(Login);
【问题讨论】:
标签: reactjs react-redux