class SubCategories extends React.Component<
SubCategoryStateProps
> {
constructor(props: RouteComponentProps<CategoryUrlParams>) {
super(props);
this.state = {
category: null,
};
}
componentDidMount() {
axios
.get(
window.location.origin + `/core/academix/categories/${this.CategoryId}`
)
.then((result: AxiosResponse<Category>) => {
if (result.status == 200) {
this.setState({
category: result.data,
});
}
})
.catch((error) => {
handleApiError(
error,
'Something went wrong when trying to load category details'
);
});
};
render() { <Title level={3}>{this.state.category.translations[1].name}</Title>);
}
}
export default SubCategories;
在初始状态下,我将 the 设置category
为 null,然后在 SubCategoryStateProps 中Categpry | null
设置了category
with 的新状态,axios
但在渲染之后它仍然说 category 是null
为什么?
出现问题axios.get
是因为是异步调用,执行需要时间。同时,初始渲染被调用。由于this.state.category
仍然是null
(因为axios.get
没有完全执行)它会抛出一个错误。
简单地认为这两个(axios.get
和render
)并行运行。
您所要做的就是在渲染中进行空检查。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句