Trying to educate in React.(尝试在React中进行教育。)
It might be the case, that the whole structure is wrong however, this is it:(可能是这样,整个结构是错误的,是这样的:)
LoginComponent contains LoginForm, and passes onSubmit event down to the form.(LoginComponent包含LoginForm,并将onSubmit事件传递到表单。) The submitForm triggers an actionCreator, that is why I have to use this.props.login
.(SubmitForm会触发一个actionCreator,这就是为什么我必须使用this.props.login
。) But when the call is happening this
is undefined
.(但是当呼叫发生时, this
是undefined
。) I'm doing this, since LoginComponent will become an Auth component and contain the registration form as well.(我正在执行此操作,因为LoginComponent将成为Auth组件,并且还包含注册表格。) But is it correct in general?(但这是正确的吗?)
import React from 'react';
import {connect} from "react-redux";
import {userActions} from "../../actions/auth.actions";
import LoginForm from "./loginForm";
class LoginComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: ''
}
}
submitForm(username, password) {
this.props.login(username, password);
}
render() {
return (
<>
<LoginForm onSubmit={this.submitForm}/>
</>
);
}
}
const mapStateProps = state => {
const {isLoggedIn, isLoggingIn, user} = state;
return {isLoggedIn, isLoggingIn, user};
};
const actionCreators = {
login: userActions.login,
};
const connectedLoginComponent = connect(mapStateProps, actionCreators)(LoginComponent);
export {connectedLoginComponent as Login};
LoginForm:(登录表格:)
import React, {useState} from 'react';
import PropTypes from 'prop-types';
const LoginForm = (props) => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const { onSubmit } = props;
const handleSubmit = (e) => {
e.preventDefault();
onSubmit(username, password);
};
return (
<>
<form onSubmit={e => handleSubmit(e)}>
<input
onChange={e => setUsername(e.target.value)}
value={username}
name={"username"}
type="text"
placeholder={'Username'}
required
/>
<input
onChange={e => setPassword(e.target.value)}
value={password}
name={"password"}
type="text"
placeholder={'Password'}
required
/>
<button>Login</button>
</form>
</>
);
};
LoginForm.propTypes = {
onSubmit: PropTypes.func,
};
export default LoginForm;
ask by Animus translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…