【发布时间】: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 的一些绑定问题,但不是。
【问题讨论】:
-
你能在 Stackblitz 上创建一个minimal reproducible example 吗?
标签: javascript reactjs typescript axios