【问题标题】:How to create a custom hook to post to an API and store result?如何创建自定义挂钩以发布到 API 并存储结果?
【发布时间】:2021-05-12 00:22:28
【问题描述】:

我有一个登录表单,它使用useState 挂钩来存储输入的(用户名和密码)状态,因此我可以将此数据传递给使用createAsyncThunk 的函数,该函数发布到 API 并存储其结果。

目前这是我所拥有的:

登录.tsx

import React, { useState } from 'react';
import {
  Avatar,
  Button,
  Checkbox,
  Container,
  CssBaseline,
  FormControlLabel,
  Grid,
  Link,
  TextField,
  Typography,
} from '@material-ui/core';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import { makeStyles } from '@material-ui/core/styles';
import { useAuth } from '../hooks';
import { useHistory } from 'react-router';
import { authManager } from '../authManager';

const useStyles = makeStyles((theme) => ({
  //...
}));

const Login: React.FC = () => {
  const classes = useStyles();
  const { push } = useHistory();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const handleUsername: React.ChangeEventHandler<HTMLInputElement> = (e) =>
    setUsername(e.target.value);
  const handlePassword: React.ChangeEventHandler<HTMLInputElement> = (e) =>
    setPassword(e.target.value);

  const SignIn = async () => {
    await useAuth(username, password);
  };

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div className={classes.paper}>
        <Avatar className={classes.avatar}>
          <LockOutlinedIcon />
        </Avatar>
        <Typography component="h1" variant="h5">
          Sign in
        </Typography>
        <form className={classes.form} noValidate>
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            id="email"
            label="E-mail"
            name="email"
            autoComplete="email"
            value={username}
            onChange={handleUsername}
            autoFocus
          />
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            name="password"
            label="Senha"
            type="password"
            id="password"
            autoComplete="current-password"
            value={password}
            onChange={handlePassword}
          />
          <Button
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
            onClick={SignIn}
          >
            Sign In
          </Button>
        </form>
      </div>
    </Container>
  );
};

export default Login;

useAuth.ts(自定义挂钩)

import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { authOperations } from 'src/features/auth/redux/';
import { getAuth } from 'src/features/auth/redux/authSelector';

export default (username: string, password: string) => {
  const dispatch = useDispatch();
  const auth = useSelector(getAuth);

  useEffect(() => {
    dispatch(
      authOperations.getAccessToken({
        username,
        password,
      })
    );
  }, [dispatch, username, password]);

  return {
    auth,
  };
};

这不起作用,实际上我收到了Invalid hook call. Hooks can only be called inside of the body of a function component. 错误。

那么,如何通过单击按钮触发自定义钩子方法?

【问题讨论】:

    标签: reactjs typescript react-redux react-hooks


    【解决方案1】:

    我认为当您调用 useAuth 时,它会返回您稍后要调用的函数。

    例如,之后

    const [password, setPassword] = useState('');
    

    你可以放

    const [password, setPassword] = useState('');
    const auth = useAuth();
    

    然后你可以在 SignIn 函数中调用 auth(),而不是在那里调用 useAuth。

    在那之后您可能还有其他一些问题需要解决,但这应该会让您走上正轨。

    【讨论】:

      猜你喜欢
      • 2020-05-28
      • 2012-07-08
      • 2023-01-18
      • 2023-01-24
      • 2022-12-10
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2023-02-24
      相关资源
      最近更新 更多