【问题标题】:TypeError: is not a function with React, Typescript and AxiosTypeError:不是 React、Typescript 和 Axios 的函数
【发布时间】:2022-10-19 06:00:11
【问题描述】:

所以,我搜索了一个现有的解决方案,但我什么也没找到,或者我没有找到正确的方法,因此,如果有关于它的现有线程,我很抱歉。

总而言之,当我的代码来自对后端的 Axios 调用时,似乎我的代码没有将对象正确地实例化为一个类。所以,当我调用某个函数时,我得到了错误Uncaught TypeError TypeError: object.method is not a function

例子:

首先,基本上,父组件将调用向后端发出请求的服务。然后将结果传递给子组件。

// imports
const Component: React.FC<ComponentProps> = () => {
  const { id } = useParams<{ id: string }>();
  const [object, setObject] = useState<Class>(new Class());
  
    useEffect(() => {
        (async () => {
            try {
                const object = await Service.getById(id);
                setObject(object);
            } catch (err) {
                //error handling
            } finally {
                cleanup();
            }
        })();

        return () => {
            // cleanup
        };
    });

  return  (
    <Container title={object.name}>
          <Child object={object} />
    </Container>
  );
};

export default Component;

然后,在子组件中,假设我尝试调用在类中定义的方法,我得到not a function 错误:

// imports
interface Interface {
  object: Class;
}

const Child: React.FC<Interface> = ({ object }) => {

  object.callSomeFunction(); // error starts here

  return (
    <SomeJSXCode />
  );
};

export default Child;

类代码示例,我尝试将方法编写为函数、箭头函数和 getter,但没有一个起作用。此外,作为一种解决方法,我一直在定义一种方法来实例化对象并设置所有属性,但我认为这不是一个好的长期解决方案,并且对于具有许多属性的类,它会变得很大:

export class Class {
  id: string = '';
  name: string = '';
  callSomeFunction = () => {
    // do something;
  }
  static from(object: Class): Class {
    const newInstance = new Class();
    newInstance.id = object.id;
    newInstance.name = object.name;
    // imagine doing this for a class with many attributes
    return newInstance;
  }
}

最后,Service 代码如有必要更好理解:

// imports

const URL = 'http://localhost:8000';

const baseConfig: AxiosRequestConfig = {
  baseURL: URL,
  headers: { 'Content-Type': 'application/json' },
  withCredentials: true,
};

export const backend = axios.create({
  ...baseConfig,
  baseURL: URL + '/someEndpoint',
});

export const Service = {
  async getById(id: string): Promise<Class> {
      try {
        const { data } = await backend.get<Class>(`/${id}`);
        return data;
      } catch (err) {
        throw new Error(err.response.data.message);
    }
  },
};

由于隐私原因,我无法分享真实代码,请让我知道这是否足够或是否需要更多信息。提前致谢。

我认为这是here 的一些绑定问题,但不是。

【问题讨论】:

标签: javascript reactjs typescript axios


【解决方案1】:

所以,我实际上通过更新后端的类验证器来解决这个问题,因为解析只需要将字符串解析为数字。但是,通过将注释 @Type(() =&gt; Number) 添加到我的 dtos,我将不再需要解析字符串。

【讨论】:

    猜你喜欢
    • 2021-04-04
    • 1970-01-01
    • 2020-08-18
    • 2020-08-25
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    相关资源
    最近更新 更多