我在一个表单页使用了 函数组件,然后使用了hooks(useReducer) 管理状态, 但是我需要异步请求接口做字段检查,请问我该如何绑定事件?
function Login(){
const classes = useStyles();
const [state, updateState] = React.useReducer(enhancedReducer, initialState);
const updateForm = React.useCallback( ({target: {value, name, type}}) => {
const updatePath = name.split('.')
if (updatePath.length === 1) {
const [key] = updatePath
updateState({
[key]: value
});
}
if (updatePath.length === 2) {
updateState({
_path: updatePath,
_value: value
})
}
});
// function onCheckUsername()
// {
// // 验证一下用户名
// checkAccount({ 'member': state.username.val }).then(response => {
// let tmp = state;
// switch (response.status) {
// case 201:
// tmp.username.help = '';
// tmp.password.isShow = true;
// // 展示
// break;
// case 202:
// tmp.username.helptext = '123213213213';
// tmp.username.error = true;
// setStates(tmp);
// break;
// default:
// tmp.username.helptext = 'default';
// break;
// }
// console.log(tmp, response.status);
//
// console.log(response);
// }).catch( error => {
// console.log(error);
// })
// }
return (
<ThemeProvider theme={theme}>
<Card className={ classes.root }>
<LinearProgress />
<CardContent>
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
{/* <Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar> */}
<Typography component="h1" variant="h5">
{ state.title }
</Typography>
<form className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
error={state.username.error}
helperText={state.username.helptext}
onChange={ updateForm }
autoFocus
/>
{ state.password.isShow && <TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
/> }
{/* <FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Remember me"
/> */}
<Grid container>
<Grid className={classes.subject} item xs={8}>
<Link href="#" color="inherit" variant="body2">
忘记密码?
</Link>
<span className={classes.aboutFive}>or</span>
<Link color="secondary" href="#" variant="body2">
注册
</Link>
</Grid>
<Grid item xs={1}></Grid>
<Grid item xs={3}>
<Button
type="button"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
disableElevation
onClick={onCheckUsername}
>
下一步
</Button>
</Grid>
</Grid>
<SignWith />
</form>
</div>
</Container>
</CardContent>
</Card>
</ThemeProvider>
);
}
我现在的做法是在function中套function 这样肯定不太对 请问我该如何在 function 组件中 绑定 onCheckUsername 事件?