无法设置状态挂钩

时间:2020-10-15 15:40:49

标签: reactjs axios react-hooks

我有一个钩子

import { useState, useEffect } from 'react';

export default (httpClient) => {
  const [error, setError] = useState(null);

  const reqInterceptor = httpClient.interceptors.request.use((req) => {
    setError(null);
    return req;
  });

  const resInterceptor = httpClient.interceptors.response.use(
    (res) => res,
    (err) => {
      setError(err);
      console.log(err);
    }
  );
  console.log(error);

  useEffect(() => {
    return () => {
      httpClient.interceptors.request.eject(reqInterceptor);
      httpClient.interceptors.response.eject(resInterceptor);
    };
  }, [
    httpClient.interceptors.request,
    httpClient.interceptors.response,
    reqInterceptor,
    resInterceptor,
  ]);

  const errorConfirmedHandler = () => {
    setError(null);
  };

  return [error, errorConfirmedHandler];
};

此钩子处理错误;当发生错误时,我可以使用console.log(err)来获取它,但是serError()并没有设置状态。 有什么问题吗?

我正在使用钩子将此基于类的组件转换为功能组件:

class extends Component {
    constructor(props) {
      super(props);
      this.state = {
        error: null,
      };
      this.err = () => {
        this.reqInterceptor = axios.interceptors.request.use((req) => {
          this.setState({ error: null });
          return req;
        });

        this.resInterceptor = axios.interceptors.response.use(
          (res) => res,
          (err) => {
            this.setState({ error: err });
          }
        );
      };
    }

    componentWillUnmount() {
      axios.interceptors.request.eject(this.reqInterceptor);
      axios.interceptors.response.eject(this.resInterceptor);
    }

    errorConfirmedHandler = () => {
      this.setState({ error: null });
    };


    render() {
      this.err();
      return (jsx)
  }

我有componentWillUnmount,所以我不喜欢将其保留为基于类的组件,但这使我成功了。转换很明显,我在err 旁边记录了setError(),可以,但是状态始终为null

0 个答案:

没有答案