我正在尝试为注册表单设置错误消息,但因为我使用的是 Material UI,所以我必须为我的项目使用功能组件。我正在关注 YouTube 上的教程,但那家伙正在使用类组件。我设法将大部分代码转换为功能组件,但我迷失在 componentDidUpdate 函数中。
我也尝试使用 useEffect 函数,但无济于事,当有人单击提交按钮(如果他们没有输入任何字段)时,我无法显示警报/消息错误。我还收到一个错误,即消息未在 SignUp 组件内的 Alert 组件中定义,尽管它已在 useState 函数中定义。
{msg ? <Alert color="danger">{msg}</Alert> : null}
下面是 SignUp 组件的代码
import React, { useState, useEffect } from "react";
import Avatar from "@material-ui/core/Avatar";
import Button from "@material-ui/core/Button";
import CssBaseline from "@material-ui/core/CssBaseline";
import TextField from "@material-ui/core/TextField";
import Link from "@material-ui/core/Link";
import Grid from "@material-ui/core/Grid";
import Box from "@material-ui/core/Box";
import Typography from "@material-ui/core/Typography";
import { makeStyles } from "@material-ui/core/styles";
import Container from "@material-ui/core/Container";
import Logo from "./assets/images/logo_transparent.png";
import { Alert } from "reactstrap";
//redux
import { connect } from "react-redux";
//proptypes
import PropTypes from "prop-types";
import { register } from "./actions/authActions";
const useStyles = makeStyles(theme => ({
//styles- for brevity only
}));
function SignUp(props) {
const classes = useStyles();
const [form, setValues] = useState({
name: "",
email: "",
password: "",
msg: null
});
// Similar to componentDidMount and componentDidUpdate
//By running an empty array [] as a second argument,
//we’re letting React know that the useEffect function doesn’t
//depend on any values from props or state.
useEffect(() => {
const { error } = props;
if (error !== form.error) {
//check for register error
if (error.id === "REGISTER_FAIL") {
setValues({ msg: error.msg.msg });
} else {
setValues({ msg: null });
}
}
}, []);
const onChange = e => {
setValues({
...form,
[e.target.name]: e.target.value,
[e.target.email]: e.target.value,
[e.target.password]: e.target.value
});
};
const handleClick = e => {
e.preventDefault();
const { name, email, password } = form;
//create user object
const newUser = {
name,
email,
password
};
//attempt to register
props.register(newUser);
window.confirm("Registration details: " + name + " " + email);
//window.location.href = "http://localhost:3000/";
};
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
{msg ? <Alert color="danger">{msg}</Alert> : null}
<form className={classes.form} noValidate>
<Grid container spacing={2}>
<Grid item xs={12}>
<TextField
autoComplete="name"
name="name"
variant="outlined"
required
fullWidth
id="name"
label="Full Name"
autoFocus
onChange={onChange}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
onChange={onChange}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="password"
label="Password"
type="password"
autoComplete="current-password"
onChange={onChange}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
name="cpassword"
label="Confirm Password"
type="password"
id="cpassword"
autoComplete="confirm-password"
/>
</Grid>
<Grid item xs={12} />
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
onClick={handleClick}
>
Sign Up
</Button>
<Button
href="http://localhost:3000/"
fullWidth
variant="contained"
color="primary"
className={classes.home}
>
Home
</Button>
<br />
<br />
<Grid container justify="flex-end">
<Grid item>
<Link href="http://localhost:3000/signin" variant="body2">
Already have an account? Sign in
</Link>
</Grid>
</Grid>
</form>
</div>
<Box mt={5}>
</Box>
</Container>
);
}
SignUp.propTypes = {
isAuthenticated: PropTypes.bool,
error: PropTypes.object.isRequired,
register: PropTypes.func.isRequired
};
const mapStateToProps = state => ({
isAuthenticated: state.auth.isAuthenticated,
error: state.error //getting from reducer
});
export default connect(
mapStateToProps,
{ register } //from redux actions //mapdispatchtoprop
)(SignUp); //component
这是原来的componentDidUpdate函数
componentDidUpdate(prevProps) {
const {error} = this.props;
if(error !== prevProps.error){
//check for register error
if(error.id === "REGISTER_FAIL"){
this.setState({msg:error.msg.msg});
}else {
setValues({ msg: null });
}
}
}
最佳答案
当您将 useEffect
视为一个在使用 componentDidUpdate
等“副作用”(改变状态)时运行的函数时,您需要留意error
和 msg
状态。
而不是
// Similar to componentDidMount and componentDidUpdate
//By running an empty array [] as a second argument,
//we’re letting React know that the useEffect function doesn’t
//depend on any values from props or state.
useEffect(() => {
const { error } = props;
if (error !== form.error) {
//check for register error
if (error.id === "REGISTER_FAIL") {
setValues({ msg: error.msg});
} else {
setValues({ msg: null });
}
}
}, []);
你需要做
useEffect(() => {
const { error } = props;
if (error !== form.error) {
//check for register error
if (error.id === "REGISTER_FAIL") {
- setValues(({ msg: error.msg});
+ setValues({ ...form, msg: error.msg});
} else {
- setValues({ msg: null });
+ setValues({ ...form, msg: null });
}
}
}, [error, form.msg]);
我像 setValues({ ...form, msg: error.msg.msg })
一样传播 ...form
的原因是因为更新函数 (由 React.useState
返回的第二个参数)不会更新状态中的其他属性。
因此 setValues({ msg: null });
会将 form
从
{
name: 'previous name',
password: 'previous password',
email: 'previous email',
msg: 'previous message...'
}
进入{msg: null}
,删除名称、电子邮件、密码
属性。
由于 React.useState
的更新器(“别名”为 React documentation 中的 setState
)和 setState
之间的行为是不同的最终创建了 use-legay-state NPM package ,除非绝对必要,否则您可能不应该使用它。
旁注
与您的问题无关,您还想要
1. 将 name/email/password/msg
分成单独的状态
2.“或”使用useReducer钩子(Hook)。
案例 1 的实现更改
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [message, setMessage] = useState('');
如果您想继续使用对象 form
,您可能需要遵循命名约定,将 setValues
更改为 setForm
或 const [formValues, setFormValues] = useState({...})
.
您可以更新每个字段,例如,
<TextField
autoComplete="name"
name="name"
variant="outlined"
required
fullWidth
id="name"
label="Full Name"
autoFocus
value={name}
onChange={e => setName(e.target.value)}
/>
您可以使用 useCallback对于 onChange
就像这里的 onChange={useCallback(e => setName(e.target.value), [name])}
但没有必要,除非你有性能问题。一开始就从简单开始😉
而且它还会使您的 useEffect
仅依赖于 msg
。
useEffect(() => {
const { error } = props;
if (error !== form.error) {
//check for register error
if (error.id === "REGISTER_FAIL") {
setMessage(error.msg);
} else {
setMessage(null);
}
}
}, [error, message]);
这里我将 setValues
更改为 setMessage
并将依赖项数组从 [error, form]
更改为 [error, message]
.
案例 2 的实现更改
如果你想使用useReducer
,似乎需要更多工作,因为你正在更改单独的表单字段,这些字段是单独更改的。当您更新一组应一起更改的相关状态时,useReducer
效果更好。但在您的情况下,每个状态(密码/名称
等)都会随着用户输入而独立更改,因此从上面的情况 #1 开始会更容易。
关于javascript - 如何在React中的功能组件中制作与componentDidUpdate函数类似的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56723540/